Search is not available for this dataset
id
stringlengths 1
8
| text
stringlengths 72
9.81M
| addition_count
int64 0
10k
| commit_subject
stringlengths 0
3.7k
| deletion_count
int64 0
8.43k
| file_extension
stringlengths 0
32
| lang
stringlengths 1
94
| license
stringclasses 10
values | repo_name
stringlengths 9
59
|
---|---|---|---|---|---|---|---|---|
10067150 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067151 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067152 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067153 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067154 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067155 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{TemplateBinding MatchCase}"
Content="{x:Static ae:SR.SearchMatchCaseText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding WholeWords}"
Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
Margin="3" />
<CheckBox IsChecked="{TemplateBinding UseRegex}"
Content="{x:Static ae:SR.SearchUseRegexText}"
Margin="3" />
</StackPanel>
</StackPanel>
</Grid>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> use icons for match options
<DFF> @@ -15,9 +15,9 @@
</Style>
<Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path">
-
+
<Setter Property="RenderTransform">
- <RotateTransform Angle="90" />
+ <RotateTransform Angle="90" />
</Setter>
</Style>
@@ -47,10 +47,10 @@
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
- <StackPanel Grid.Column="1">
+ <StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
- Grid.Row="0">
+ Grid.Row="0">
<TextBox Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -96,7 +96,7 @@
</Button>
</StackPanel>
- <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
+ <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
@@ -134,15 +134,30 @@
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{TemplateBinding MatchCase}"
- Content="{x:Static ae:SR.SearchMatchCaseText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding WholeWords}"
- Content="{x:Static ae:SR.SearchMatchWholeWordsText}"
- Margin="3" />
- <CheckBox IsChecked="{TemplateBinding UseRegex}"
- Content="{x:Static ae:SR.SearchUseRegexText}"
- Margin="3" />
+ <ToggleButton IsChecked="{TemplateBinding MatchCase}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding WholeWords}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
+ <ToggleButton IsChecked="{TemplateBinding UseRegex}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
+ Height="24"
+ Width="24">
+ <Image Width="16"
+ Height="16"
+ Stretch="Fill"
+ Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
+ </ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
| 29 | use icons for match options | 14 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067156 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
* - `Model` A model constructor to use (must have `.toJSON()`)
*
* @param {Object} options
*/
module.exports = function(options) {
/**
* Shortcut method for
* creating lazy views.
*
* @param {Object} options
* @return {Module}
*/
function fm(options) {
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
}
fm.create = module.exports;
fm.Model = options.Model;
fm.Events = events;
fm.Module = mod(fm);
fm.define = define(fm);
fm.util = utils;
fm.modules = {};
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
this.module = this.module || options._module;
this._lookup = {};
this._children = [];
this._data = options.data || {};
// Use the template defined on
// the custom view, or use the
}
data.fm_attrs = 'id="' + this.fmid() + '"';
return this._html = this.template.render(mixin(data, this.data()));
},
render: function() {
// been passed then return the
// entire data store.
if (!key && !value) {
return this._data;
}
// If a string key has been
// passed, but no value
if (typeof key === 'string' && !value) {
return this._data[key];
}
// If the user has stated a key
// and a value. Set the value on
// the key.
if (key && value) {
this._data[key] = value;
this.trigger('datachange', key, value);
this.trigger('datachange:' + key, value);
return this;
}
// If the key is an object literal
// then we extend the data store with it.
if ('object' === typeof key) {
mixin(this._data, key);
this.trigger('datachange');
for (var prop in key) this.trigger('datachange:' + prop, key[prop]);
return this;
}
},
json.id = this.id();
json.fmid = this.fmid();
json.module = this.module;
json.data = this.data();
return json;
}
});
// Helpers
// -------
<MSG> - Added FruitMachine.Model
<DFF> @@ -293,7 +293,8 @@
this.module = this.module || options._module;
this._lookup = {};
this._children = [];
- this._data = options.data || {};
+ //this._data = options.data || {};
+ this.model = options.model || new Model(options.data || {});
// Use the template defined on
// the custom view, or use the
@@ -386,7 +387,7 @@
}
data.fm_attrs = 'id="' + this.fmid() + '"';
- return this._html = this.template.render(mixin(data, this.data()));
+ return this._html = this.template.render(mixin(data, this.model.get()));
},
render: function() {
@@ -551,31 +552,27 @@
// been passed then return the
// entire data store.
if (!key && !value) {
- return this._data;
+ return this.model.get();
}
// If a string key has been
// passed, but no value
if (typeof key === 'string' && !value) {
- return this._data[key];
+ return this.model.get(key);
}
// If the user has stated a key
// and a value. Set the value on
// the key.
if (key && value) {
- this._data[key] = value;
- this.trigger('datachange', key, value);
- this.trigger('datachange:' + key, value);
+ this.model.set(key, value);
return this;
}
// If the key is an object literal
// then we extend the data store with it.
if ('object' === typeof key) {
- mixin(this._data, key);
- this.trigger('datachange');
- for (var prop in key) this.trigger('datachange:' + prop, key[prop]);
+ this.model.set(key);
return this;
}
},
@@ -621,11 +618,47 @@
json.id = this.id();
json.fmid = this.fmid();
json.module = this.module;
- json.data = this.data();
+ json.model = this.model.get();
return json;
}
});
+ /**
+ * Model
+ *
+ * A very basic model to hold view data.
+ */
+
+ var Model = FruitMachine.Model = function(options) {
+ this._data = mixin({}, options);
+ };
+
+ mixin(Model.prototype, Events, {
+
+ get: function(key) {
+ return key ? this._data[key] : this._data;
+ },
+
+ set: function(key, value) {
+ if ('object' === key) {
+ mixin(this._data, key);
+ this.trigger('datachange');
+ for (var prop in key) this.trigger('datachange:' + prop, key[prop]);
+ } else if ('string' === typeof key && value) {
+ this._data[key] = value;
+ this.trigger('datachange', key, value);
+ this.trigger('datachange:' + key, value);
+ }
+
+ return this;
+ },
+
+ toJSON: function() {
+ return mixin({}, this._data);
+ }
+
+ });
+
// Helpers
// -------
| 44 | - Added FruitMachine.Model | 11 | .js | js | mit | ftlabs/fruitmachine |
10067157 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped).
## Browser Support
* IE9+
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
</script>
```
You can also use more advanced syntax for more options:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
.catch(function(pathsNotFound) { /* at least one didn't load */ });
```
1. Check if bundle has already been defined
```javascript
if (!loadjs.isDefined('foobar')) {
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
}
```
1. Fetch files in parallel and load them in series
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() { /* foo.js and bar.js loaded in series */ },
async: false
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> Update README.md
<DFF> @@ -14,6 +14,10 @@ LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simp
LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped).
+The latest version of LoadJS can be found in the `dist/` directory in this repository:
+ * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
+ * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js)
+
## Browser Support
* IE9+
| 4 | Update README.md | 0 | .md | md | mit | muicss/loadjs |
10067158 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped).
## Browser Support
* IE9+
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
</script>
```
You can also use more advanced syntax for more options:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
.catch(function(pathsNotFound) { /* at least one didn't load */ });
```
1. Check if bundle has already been defined
```javascript
if (!loadjs.isDefined('foobar')) {
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
}
```
1. Fetch files in parallel and load them in series
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() { /* foo.js and bar.js loaded in series */ },
async: false
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> Update README.md
<DFF> @@ -14,6 +14,10 @@ LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simp
LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped).
+The latest version of LoadJS can be found in the `dist/` directory in this repository:
+ * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
+ * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js)
+
## Browser Support
* IE9+
| 4 | Update README.md | 0 | .md | md | mit | muicss/loadjs |
10067159 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
// add cross origin script for file2
if (path === 'assets/file2.js') {
el.crossOrigin = 'anonymous';
}
},
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
done();
});
});
});
});
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> added Promise support via returnPromise argument
<DFF> @@ -647,5 +647,81 @@ describe('LoadJS tests', function() {
done();
});
});
+
+
+ it('should return Promise object if returnPromise is true', function() {
+ var prom = loadjs(['assets/file1.js'], {returnPromise: true});
+
+ // verify that response object is a Promise
+ assert.equal(prom instanceof Promise, true);
+ });
+
+
+ it('Promise object should support resolutions', function(done) {
+ var prom = loadjs(['assets/file1.js'], {returnPromise: true});
+
+ prom.then(function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ done();
+ });
+ });
+
+
+ it('Promise object should support rejections', function(done) {
+ var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
+
+ prom.then(
+ function(){},
+ function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ );
+ });
+
+
+ it('Promise object should support catches', function(done) {
+ var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
+
+ prom
+ .catch(function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ });
+ });
+
+
+ it('supports Promises and success callbacks', function(done) {
+ var numCompleted = 0;
+
+ function completedFn() {
+ numCompleted += 1;
+ if (numCompleted === 2) done();
+ };
+
+ var prom = loadjs('assets/file1.js', {
+ success: completedFn,
+ returnPromise: true
+ });
+
+ prom.then(completedFn);
+ });
+
+
+ it('supports Promises and bundle ready events', function(done) {
+ var numCompleted = 0;
+
+ function completedFn() {
+ numCompleted += 1;
+ if (numCompleted === 2) done();
+ };
+
+ loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
+ .then(completedFn);
+
+ loadjs.ready('bundle1', completedFn);
+ });
});
});
| 76 | added Promise support via returnPromise argument | 0 | .js | js | mit | muicss/loadjs |
10067160 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
// add cross origin script for file2
if (path === 'assets/file2.js') {
el.crossOrigin = 'anonymous';
}
},
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
done();
});
});
});
});
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> added Promise support via returnPromise argument
<DFF> @@ -647,5 +647,81 @@ describe('LoadJS tests', function() {
done();
});
});
+
+
+ it('should return Promise object if returnPromise is true', function() {
+ var prom = loadjs(['assets/file1.js'], {returnPromise: true});
+
+ // verify that response object is a Promise
+ assert.equal(prom instanceof Promise, true);
+ });
+
+
+ it('Promise object should support resolutions', function(done) {
+ var prom = loadjs(['assets/file1.js'], {returnPromise: true});
+
+ prom.then(function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ done();
+ });
+ });
+
+
+ it('Promise object should support rejections', function(done) {
+ var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
+
+ prom.then(
+ function(){},
+ function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ );
+ });
+
+
+ it('Promise object should support catches', function(done) {
+ var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
+
+ prom
+ .catch(function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ });
+ });
+
+
+ it('supports Promises and success callbacks', function(done) {
+ var numCompleted = 0;
+
+ function completedFn() {
+ numCompleted += 1;
+ if (numCompleted === 2) done();
+ };
+
+ var prom = loadjs('assets/file1.js', {
+ success: completedFn,
+ returnPromise: true
+ });
+
+ prom.then(completedFn);
+ });
+
+
+ it('supports Promises and bundle ready events', function(done) {
+ var numCompleted = 0;
+
+ function completedFn() {
+ numCompleted += 1;
+ if (numCompleted === 2) done();
+ };
+
+ loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
+ .then(completedFn);
+
+ loadjs.ready('bundle1', completedFn);
+ });
});
});
| 76 | added Promise support via returnPromise argument | 0 | .js | js | mit | muicss/loadjs |
10067161 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
(function() {
'use strict';
// Create local references to some methods
var slice = Array.prototype.slice;
var has = Object.prototype.hasOwnProperty;
// Determine if we have a DOM
// in the current environment.
var hasDom = (typeof document !== 'undefined');
/**
* VIEW
*/
var FruitMachine = function(options) {
return new View(options);
};
/**
// Current Version
FruitMachine.VERSION = '0.0.1';
// Global data store
var store = FruitMachine.store = {
modules: {},
templates: {},
helpers: {}
};
// Utilities
var util = FruitMachine.util = {
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
* @param {Number} index
* @return void
*/
insert: function(item, array, index) {
if (typeof index !== 'undefined') {
array.splice(index, 0, item);
store.helpers[name] = helper;
};
FruitMachine.helper.clear = function(name) {
delete store.helpers[name];
};
/**
FruitMachine.templates = function(templates) {
var type = typeof templates;
if ('object' === type) mixin(store.templates, templates);
else if ('function' === type) getTemplate = templates;
};
/**
* @param {String} module
* @return {Template}
*/
var getTemplate = function(module) {
return store.templates[module];
};
var View = FruitMachine.View = function(options) {
options = mixin({}, options);
if (options.module) return create(options);
this._configure(options);
this.add(options.children);
this.onInitialize(options);
this.trigger('initialize', [options], { propagate: false });
};
*/
function create(options) {
var Module = store.modules[options.module] || FruitMachine;
options._module = options.module;
delete options.module;
return new Module(options);
}
this.propagate = false;
};
// Mixin Events and extend the prototype
mixin(View.prototype, {
on: Events.on,
off: Events.off,
onTeardown: function() {},
onDestroy: function() {},
/**
* Configures the new View
* with the options passed
* to the constructor.
*
* @param {Object} options
* @api private
*/
_configure: function(options) {
this._id = options.id || util.uniqueId('auto_');
this._fmid = options.fmid || util.uniqueId('fmid');
this.tag = this.tag || options.tag || 'div';
this.classes = this.classes || options.classes || [];
this._module = this._module || options._module;
this.template = this.getTemplate();
this._lookup = {};
this._children = [];
this.helpers = this.helpers || options.helpers || [];
// Use the model passed in, or create
// a model from the data passed in.
this.model = options.model || new Model(options.data || {});
// Purge html caches when the model is changed
this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this);
this.model.on('change', this.purgeHtmlCache);
// Init helpers
this.helpers.forEach(function(helper) {
// Allow helpers to be passed in as
// string references to earlier registered
// helpers, or passed in directly as a function.
helper = ('function' === typeof helper)
? helper
: store.helpers[helper];
// Run the helper function
if (helper) helper(this, FruitMachine);
}, this);
},
getTemplate: function() {
// Use the template defined on the
// custom view, or use the template getter.
this.template = this.template || getTemplate(this._module);
// Warn if no template found
if (!this.template) return console.log('FM - No template for %s', this._module);
// Accomodate for template.render() or template()
// this.template.render has to be bound to stop
// a hogan.js error if the context is wrong.
return this.template.render ? util.bind(this.template.render, this.template) : this.template;
},
add: function(children, options) {
}
},
id: function(id) {
return id ? this._lookup[id] : this._id;
},
/**
* Example:
*
* var child = view.child(<id>);
*
* // or
*
* var child = view.child(<module>);
*
* @param {String} name [id|module]
* // Return all direct children
* view.children();
*
* // Return all descendant children
* // that match query.
* view.children('orange');
*
* // Loop direct children like forEach style.
* // Not sure if this is neccessary or not?
* // Could be depricated.
* view.children(function(child) { ... });
*
* @param {undefined|String|Function} query
* @return {Array}
*/
// Wrap the html in a FruitMachine
// generated root element and return.
return this.html = this.wrapHTML(html);
},
wrapHTML: function(html) {
return '<' + this.tag + ' class="' + this._module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>';
},
<MSG> Many small refinements
<DFF> @@ -31,18 +31,6 @@
(function() {
'use strict';
- // Create local references to some methods
- var slice = Array.prototype.slice;
- var has = Object.prototype.hasOwnProperty;
-
- // Determine if we have a DOM
- // in the current environment.
- var hasDom = (typeof document !== 'undefined');
-
- /**
- * VIEW
- */
-
var FruitMachine = function(options) {
return new View(options);
};
@@ -50,13 +38,21 @@
// Current Version
FruitMachine.VERSION = '0.0.1';
- // Global data store
+ // Global data store
var store = FruitMachine.store = {
modules: {},
templates: {},
helpers: {}
};
+ // Create local references to some methods
+ var slice = Array.prototype.slice;
+ var has = Object.prototype.hasOwnProperty;
+
+ // Determine if we have a DOM
+ // in the current environment.
+ var hasDom = (typeof document !== 'undefined');
+
// Utilities
var util = FruitMachine.util = {
@@ -100,7 +96,6 @@
* @param {Number} index
* @return void
*/
-
insert: function(item, array, index) {
if (typeof index !== 'undefined') {
array.splice(index, 0, item);
@@ -290,8 +285,16 @@
store.helpers[name] = helper;
};
+ /**
+ * Clears one or all
+ * registered helpers.
+ *
+ * @param {String} name
+ * @api public
+ */
FruitMachine.helper.clear = function(name) {
- delete store.helpers[name];
+ if (name) delete store.helpers[name];
+ else store.helpers = {};
};
/**
@@ -309,7 +312,7 @@
FruitMachine.templates = function(templates) {
var type = typeof templates;
if ('object' === type) mixin(store.templates, templates);
- else if ('function' === type) getTemplate = templates;
+ else if ('function' === type) FruitMachine.templates.get = templates;
};
/**
@@ -321,15 +324,55 @@
* @param {String} module
* @return {Template}
*/
- var getTemplate = function(module) {
+ var getTemplate = FruitMachine.templates.get = function(module) {
return store.templates[module];
};
+ /**
+ * Clear reference to a module's
+ * template, or clear all template
+ * references and resets the template
+ * getter method.
+ *
+ * @param {String|undefined} module
+ * @api public
+ */
+ FruitMachine.templates.clear = function(module) {
+ if (module) delete store.templates[module];
+ else {
+ store.templates = {};
+ FruitMachine.templates.get = getTemplate;
+ }
+ };
+
+ /**
+ * View
+ */
+
+ /**
+ * View constructor
+ *
+ * @constructor
+ * @param {Object} options
+ * @api public
+ */
var View = FruitMachine.View = function(options) {
+
+ // Shallow clone the options
options = mixin({}, options);
+
+ // If a `module` property is passed
+ // we create a view of that module type.
if (options.module) return create(options);
+
+ // Various config steps
this._configure(options);
+
+ // Add any children passed
+ // in the options object
this.add(options.children);
+
+ // Run initialize hooks
this.onInitialize(options);
this.trigger('initialize', [options], { propagate: false });
};
@@ -348,8 +391,10 @@
*/
function create(options) {
var Module = store.modules[options.module] || FruitMachine;
+
options._module = options.module;
delete options.module;
+
return new Module(options);
}
@@ -357,8 +402,42 @@
this.propagate = false;
};
- // Mixin Events and extend the prototype
+ // Extend the prototype
mixin(View.prototype, {
+
+ /**
+ * Configures the new View
+ * with the options passed
+ * to the constructor.
+ *
+ * @param {Object} options
+ * @api private
+ */
+ _configure: function(options) {
+ this._id = options.id || util.uniqueId('auto_');
+ this._fmid = options.fmid || util.uniqueId('fmid');
+ this.tag = options.tag || this.tag || 'div';
+ this.classes = this.classes || options.classes || [];
+ this._module = this._module || options._module;
+ this.helpers = this.helpers || options.helpers || [];
+ this.template = this.getTemplate();
+ this._lookup = {};
+ this._children = [];
+
+ // Use the model passed in,
+ // or create a model from
+ // the data passed in.
+ this.model = options.model || new Model(options.data || {});
+
+ // Attach helpers
+ this.helpers.forEach(this.attachHelper, this);
+
+ // Purge html caches when the model is changed
+ this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this);
+ this.model.on('change', this.purgeHtmlCache);
+ },
+
+ // Events
on: Events.on,
off: Events.off,
@@ -415,60 +494,32 @@
onTeardown: function() {},
onDestroy: function() {},
- /**
- * Configures the new View
- * with the options passed
- * to the constructor.
- *
- * @param {Object} options
- * @api private
- */
- _configure: function(options) {
- this._id = options.id || util.uniqueId('auto_');
- this._fmid = options.fmid || util.uniqueId('fmid');
- this.tag = this.tag || options.tag || 'div';
- this.classes = this.classes || options.classes || [];
- this._module = this._module || options._module;
- this.template = this.getTemplate();
- this._lookup = {};
- this._children = [];
- this.helpers = this.helpers || options.helpers || [];
-
- // Use the model passed in, or create
- // a model from the data passed in.
- this.model = options.model || new Model(options.data || {});
+ attachHelper: function(helper) {
+ // Allow helpers to be passed in as
+ // string references to earlier registered
+ // helpers, or passed in directly as a function.
+ helper = ('function' === typeof helper)
+ ? helper
+ : store.helpers[helper];
- // Purge html caches when the model is changed
- this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this);
- this.model.on('change', this.purgeHtmlCache);
-
- // Init helpers
- this.helpers.forEach(function(helper) {
-
- // Allow helpers to be passed in as
- // string references to earlier registered
- // helpers, or passed in directly as a function.
- helper = ('function' === typeof helper)
- ? helper
- : store.helpers[helper];
-
- // Run the helper function
- if (helper) helper(this, FruitMachine);
- }, this);
+ // Run the helper function
+ if (helper) helper(this, FruitMachine);
},
getTemplate: function() {
// Use the template defined on the
// custom view, or use the template getter.
- this.template = this.template || getTemplate(this._module);
+ var template = this.template || FruitMachine.templates.get(this._module);
// Warn if no template found
- if (!this.template) return console.log('FM - No template for %s', this._module);
+ if (!template) return console.warn('FM - No template for %s', this._module);
// Accomodate for template.render() or template()
// this.template.render has to be bound to stop
// a hogan.js error if the context is wrong.
- return this.template.render ? util.bind(this.template.render, this.template) : this.template;
+ return template.render
+ ? util.bind(template.render, template)
+ : template;
},
add: function(children, options) {
@@ -523,8 +574,19 @@
}
},
+ /**
+ * Returns a decendent module
+ * by id, or if called with no
+ * arguments, returns this view's id.
+ *
+ * @param {String|undefined} id
+ * @return {View|String}
+ * @api public
+ */
id: function(id) {
- return id ? this._lookup[id] : this._id;
+ return id
+ ? this.module(id)
+ : this._id;
},
/**
@@ -534,9 +596,6 @@
* Example:
*
* var child = view.child(<id>);
- *
- * // or
- *
* var child = view.child(<module>);
*
* @param {String} name [id|module]
@@ -571,15 +630,9 @@
* // Return all direct children
* view.children();
*
- * // Return all descendant children
- * // that match query.
+ * // Return all children that match query.
* view.children('orange');
*
- * // Loop direct children like forEach style.
- * // Not sure if this is neccessary or not?
- * // Could be depricated.
- * view.children(function(child) { ... });
- *
* @param {undefined|String|Function} query
* @return {Array}
*/
@@ -655,10 +708,10 @@
// Wrap the html in a FruitMachine
// generated root element and return.
- return this.html = this.wrapHTML(html);
+ return this.html = this._wrapHTML(html);
},
- wrapHTML: function(html) {
+ _wrapHTML: function(html) {
return '<' + this.tag + ' class="' + this._module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>';
},
| 126 | Many small refinements | 73 | .js | js | mit | ftlabs/fruitmachine |
10067162 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067163 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067164 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067165 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067166 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067167 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067168 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067169 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067170 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067171 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067172 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067173 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067174 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067175 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067176 | <NME> TextMateColoringTransformer.cs
<BEF> using System;
using System.Buffers;
using System.Collections.Generic;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public class TextMateColoringTransformer :
GenericLineTransformer,
IModelTokensChangedListener,
ForegroundTextTransformation.IColorMap
{
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
private volatile bool _areVisualLinesValid = false;
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = SolidColorBrush.Parse(color);
}
}
Action<Exception> exceptionHandler)
: base(exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
}
}
private void TextView_VisualLinesChanged(object sender, EventArgs e)
{
try
{
if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0)
return;
_areVisualLinesValid = true;
_firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1;
_lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1;
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
public void Dispose()
{
_textView.VisualLinesChanged -= TextView_VisualLinesChanged;
}
public void SetTheme(Theme theme)
{
_theme = theme;
_brushes.Clear();
var map = _theme.GetColorMap();
foreach (var color in map)
{
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
return null;
_brushes.TryGetValue(colorId, out IBrush result);
return result;
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
try
{
if (_model == null)
return;
int lineNumber = line.LineNumber;
var tokens = _model.GetLineTokens(lineNumber - 1);
if (tokens == null)
return;
var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count);
try
{
GetLineTransformations(lineNumber, tokens, transformsInLine);
for (int i = 0; i < tokens.Count; i++)
{
if (transformsInLine[i] == null)
continue;
transformsInLine[i].Transform(this, line);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
transformations[i] = null;
continue;
}
var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
int foreground = 0;
int background = 0;
int fontStyle = 0;
foreach (var themeRule in _theme.Match(token.Scopes))
{
if (foreground == 0 && themeRule.foreground > 0)
foreground = themeRule.foreground;
if (background == 0 && themeRule.background > 0)
background = themeRule.background;
if (fontStyle == 0 && themeRule.fontStyle > 0)
fontStyle = themeRule.fontStyle;
}
if (transformations[i] == null)
transformations[i] = new ForegroundTextTransformation();
transformations[i].ColorMap = this;
transformations[i].ExceptionHandler = _exceptionHandler;
transformations[i].StartOffset = lineOffset + startIndex;
transformations[i].EndOffset = lineOffset + endIndex;
transformations[i].ForegroundColor = foreground;
transformations[i].BackgroundColor = background;
transformations[i].FontStyle = fontStyle;
}
}
public void ModelTokensChanged(ModelTokensChangedEvent e)
{
if (e.Ranges == null)
return;
if (_model == null || _model.IsStopped)
return;
int firstChangedLineIndex = int.MaxValue;
int lastChangedLineIndex = -1;
foreach (var range in e.Ranges)
{
firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex);
lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex);
}
if (_areVisualLinesValid)
{
bool changedLinesAreNotVisible =
((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) ||
(firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex));
if (changedLinesAreNotVisible)
return;
}
Dispatcher.UIThread.Post(() =>
{
int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex);
int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex);
int totalLines = _document.Lines.Count - 1;
firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines);
lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines);
DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw];
DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine];
_textView.Redraw(
firstLineToRedraw.Offset,
(lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset);
});
}
static int Clamp(int value, int min, int max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
}
static string NormalizeColor(string color)
{
if (color.Length == 9)
{
Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] };
return normalizedColor.ToString();
}
return color;
}
}
}
<MSG> tokenize at render time if required.
<DFF> @@ -23,7 +23,7 @@ namespace AvaloniaEdit.TextMate
public void SetTheme(Theme theme)
{
_theme = theme;
-
+
_brushes.Clear();
var map = _theme.GetColorMap();
@@ -31,7 +31,7 @@ namespace AvaloniaEdit.TextMate
foreach (var color in map)
{
var id = _theme.GetColorId(color);
-
+
_brushes[id] = SolidColorBrush.Parse(color);
}
}
@@ -43,6 +43,14 @@ namespace AvaloniaEdit.TextMate
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
+ var lineModel = _model.GetLines().Get(line.LineNumber - 1);
+
+ if (lineModel.IsInvalid)
+ {
+ // manual token generation...
+ _model.ForceTokenization(line.LineNumber - 1);
+ }
+
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
| 10 | tokenize at render time if required. | 2 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067177 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067178 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067179 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067180 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067181 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067182 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067183 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067184 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067185 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067186 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067187 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067188 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067189 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067190 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067191 | <NME> CaretNavigationCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media.TextFormatting;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Editing
{
internal enum CaretMovementType
{
None,
CharLeft,
CharRight,
Backspace,
WordLeft,
WordRight,
LineUp,
LineDown,
PageUp,
PageDown,
LineStart,
LineEnd,
DocumentStart,
DocumentEnd
}
internal static class CaretNavigationCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
}
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, new KeyGesture(key, modifiers), handler);
}
private static void AddBinding(RoutedCommand command, KeyGesture gesture, EventHandler<ExecutedRoutedEventArgs> handler)
{
AddBinding(command, handler);
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, gesture));
}
static CaretNavigationCommandHandler()
{
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
AddBinding(EditingCommands.MoveLeftByCharacter, KeyModifiers.None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
AddBinding(RectangleSelection.BoxSelectLeftByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
AddBinding(EditingCommands.MoveRightByWord, keymap.WholeWordTextActionModifiers, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
AddBinding(EditingCommands.SelectRightByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
AddBinding(RectangleSelection.BoxSelectRightByWord, keymap.WholeWordTextActionModifiers | KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
AddBinding(EditingCommands.MoveUpByLine, KeyModifiers.None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
AddBinding(EditingCommands.SelectUpByLine, keymap.SelectionModifiers, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
AddBinding(RectangleSelection.BoxSelectUpByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
AddBinding(EditingCommands.MoveDownByLine, KeyModifiers.None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
AddBinding(EditingCommands.SelectDownByLine, keymap.SelectionModifiers, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
AddBinding(RectangleSelection.BoxSelectDownByLine, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
AddBinding(EditingCommands.MoveDownByPage, KeyModifiers.None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
AddBinding(EditingCommands.SelectDownByPage, keymap.SelectionModifiers, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
AddBinding(EditingCommands.MoveUpByPage, KeyModifiers.None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
AddBinding(EditingCommands.SelectUpByPage, keymap.SelectionModifiers, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLine)
AddBinding(EditingCommands.MoveToLineStart, keyGesture, OnMoveCaret(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLine)
AddBinding(EditingCommands.MoveToLineEnd, keyGesture, OnMoveCaret(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfLineWithSelection)
AddBinding(EditingCommands.SelectToLineEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
AddBinding(RectangleSelection.BoxSelectToLineStart, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
AddBinding(RectangleSelection.BoxSelectToLineEnd, KeyModifiers.Alt | keymap.SelectionModifiers, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocument)
AddBinding(EditingCommands.MoveToDocumentStart, keyGesture, OnMoveCaret(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheStartOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentStart, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocument)
AddBinding(EditingCommands.MoveToDocumentEnd, keyGesture, OnMoveCaret(CaretMovementType.DocumentEnd));
foreach (var keyGesture in keymap.MoveCursorToTheEndOfDocumentWithSelection)
AddBinding(EditingCommands.SelectToDocumentEnd, keyGesture, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
AddBinding(ApplicationCommands.SelectAll, OnSelectAll);
}
private static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.Caret.Offset = textArea.Document.TextLength;
textArea.Selection = Selection.Create(textArea, 0, textArea.Document.TextLength);
}
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaret(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
textArea.ClearSelection();
MoveCaret(textArea, direction);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretExtendSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
private static EventHandler<ExecutedRoutedEventArgs> OnMoveCaretBoxSelection(CaretMovementType direction)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.Handled = true;
// First, convert the selection into a rectangle selection
// (this is required so that virtual space gets enabled for the caret movement)
if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection))
{
textArea.Selection = textArea.Selection.IsEmpty
? new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position)
: new RectangleSelection(textArea, textArea.Selection.StartPosition,
textArea.Caret.Position);
}
// Now move the caret and extend the selection
var oldPosition = textArea.Caret.Position;
MoveCaret(textArea, direction);
textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
textArea.Caret.BringCaretToView();
}
};
}
#region Caret movement
internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
{
var desiredXPos = textArea.Caret.DesiredXPos;
textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
textArea.Caret.DesiredXPos = desiredXPos;
}
internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
{
switch (direction)
{
case CaretMovementType.None:
return caretPosition;
case CaretMovementType.DocumentStart:
desiredXPos = double.NaN;
return new TextViewPosition(0, 0);
case CaretMovementType.DocumentEnd:
desiredXPos = double.NaN;
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
var caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
var visualLine = textView.GetOrConstructVisualLine(caretLine);
var textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
switch (direction)
{
case CaretMovementType.CharLeft:
desiredXPos = double.NaN;
// do not move caret to previous line in virtual space
if (caretPosition.VisualColumn == 0 && enableVirtualSpace)
return caretPosition;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.Backspace:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
case CaretMovementType.CharRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
case CaretMovementType.WordLeft:
desiredXPos = double.NaN;
return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.WordRight:
desiredXPos = double.NaN;
return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
case CaretMovementType.LineUp:
case CaretMovementType.LineDown:
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
case CaretMovementType.LineStart:
desiredXPos = double.NaN;
return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
case CaretMovementType.LineEnd:
desiredXPos = double.NaN;
return GetEndOfLineCaretPosition(visualLine, textLine);
default:
throw new NotSupportedException(direction.ToString());
}
}
#endregion
#region Home/End
private static TextViewPosition GetStartOfLineCaretPosition(int oldVisualColumn, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine);
if (newVisualCol == 0)
newVisualCol = visualLine.GetNextCaretPosition(newVisualCol - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
if (newVisualCol < 0)
throw ThrowUtil.NoValidCaretPosition();
// when the caret is already at the start of the text, jump to start before whitespace
if (newVisualCol == oldVisualColumn)
newVisualCol = 0;
return visualLine.GetTextViewPosition(newVisualCol);
}
private static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
{
var newVisualCol = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
var pos = visualLine.GetTextViewPosition(newVisualCol);
pos.IsAtEndOfLine = true;
return pos;
}
#endregion
#region By-character / By-word movement
private static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to start of next line
var nextDocumentLine = visualLine.LastDocumentLine.NextLine;
if (nextDocumentLine != null)
{
var nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return nextLine.GetTextViewPosition(pos);
}
else
{
// at end of document
Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
}
}
}
private static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
{
var pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos >= 0)
{
return visualLine.GetTextViewPosition(pos);
}
else
{
// move to end of previous line
var previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
if (previousDocumentLine != null)
{
var previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
if (pos < 0)
throw ThrowUtil.NoValidCaretPosition();
return previousLine.GetTextViewPosition(pos);
}
else
{
// at start of document
Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
return new TextViewPosition(0, 0);
}
}
}
#endregion
#region Line+Page up/down
private static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
{
// moving up/down happens using the desired visual X position
if (double.IsNaN(xPos))
xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
// now find the TextLine+VisualLine where the caret will end up in
var targetVisualLine = visualLine;
TextLine targetLine;
var textLineIndex = visualLine.TextLines.IndexOf(textLine);
switch (direction)
{
case CaretMovementType.LineUp:
{
// Move up: move to the previous TextLine in the same visual line
// or move to the last TextLine of the previous visual line
var prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
if (textLineIndex > 0)
{
targetLine = visualLine.TextLines[textLineIndex - 1];
}
else if (prevLineNumber >= 1)
{
var prevLine = textView.Document.GetLineByNumber(prevLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.LineDown:
{
// Move down: move to the next TextLine in the same visual line
// or move to the first TextLine of the next visual line
var nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
if (textLineIndex < visualLine.TextLines.Count - 1)
{
targetLine = visualLine.TextLines[textLineIndex + 1];
}
else if (nextLineNumber <= textView.Document.LineCount)
{
var nextLine = textView.Document.GetLineByNumber(nextLineNumber);
targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
targetLine = targetVisualLine.TextLines[0];
}
else
{
targetLine = null;
}
break;
}
case CaretMovementType.PageUp:
case CaretMovementType.PageDown:
{
// Page up/down: find the target line using its visual position
var yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
if (direction == CaretMovementType.PageUp)
yPos -= textView.Bounds.Height;
else
yPos += textView.Bounds.Height;
var newLine = textView.GetDocumentLineByVisualTop(yPos);
targetVisualLine = textView.GetOrConstructVisualLine(newLine);
targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
break;
}
default:
throw new NotSupportedException(direction.ToString());
}
if (targetLine != null)
{
var yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
var newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
var targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
if (newVisualColumn >= targetLineStartCol + targetLine.Length)
{
if (newVisualColumn <= targetVisualLine.VisualLength)
newVisualColumn = targetLineStartCol + targetLine.Length - 1;
}
return targetVisualLine.GetTextViewPosition(newVisualColumn);
}
else
{
return caretPosition;
}
}
#endregion
}
}
<MSG> Merge pull request #163 from AvaloniaUI/fix-macos-keybindings
Fixed a typo
<DFF> @@ -88,7 +88,7 @@ namespace AvaloniaEdit.Editing
AddBinding(RectangleSelection.BoxSelectLeftByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
AddBinding(EditingCommands.MoveRightByCharacter, KeyModifiers.None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
AddBinding(EditingCommands.SelectRightByCharacter, keymap.SelectionModifiers, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
- AddBinding(RectangleSelection.BoxSelectRightByCharacter, keymap.SelectionModifiers | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+ AddBinding(RectangleSelection.BoxSelectRightByCharacter, KeyModifiers.Alt | keymap.SelectionModifiers, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
AddBinding(EditingCommands.MoveLeftByWord, keymap.WholeWordTextActionModifiers, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
AddBinding(EditingCommands.SelectLeftByWord, keymap.WholeWordTextActionModifiers | keymap.SelectionModifiers, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
| 1 | Merge pull request #163 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067192 | <NME> npm-debug.log <BEF> ADDFILE <MSG> Merge branch '0.2' <DFF> @@ -0,0 +1,2410 @@ +0 info it worked if it ends with ok +1 verbose cli [ 'node', '/usr/local/bin/npm', 'install', '-g', 'browserify' ] +2 info using [email protected] +3 info using [email protected] +4 verbose read json /usr/local/lib/package.json +5 verbose read json /usr/local/lib/package.json +6 verbose cache add [ 'browserify', null ] +7 verbose cache add name=undefined spec="browserify" args=["browserify",null] +8 verbose parsed url { pathname: 'browserify', +8 verbose parsed url path: 'browserify', +8 verbose parsed url href: 'browserify' } +9 silly lockFile 84c1c54e-browserify browserify +10 verbose lock browserify /Users/wilsonpage/.npm/84c1c54e-browserify.lock +11 silly lockFile 84c1c54e-browserify browserify +12 verbose addNamed [ 'browserify', '' ] +13 verbose addNamed [ null, '' ] +14 silly lockFile 80140245-browserify browserify@ +15 verbose lock browserify@ /Users/wilsonpage/.npm/80140245-browserify.lock +16 silly addNameRange { name: 'browserify', range: '', hasData: false } +17 verbose url raw browserify +18 verbose url resolving [ 'https://registry.npmjs.org/', './browserify' ] +19 verbose url resolved https://registry.npmjs.org/browserify +20 info trying registry request attempt 1 at 16:13:25 +21 verbose etag "899R1W8XNWSIDYL830UTYNK3T" +22 http GET https://registry.npmjs.org/browserify +23 http 304 https://registry.npmjs.org/browserify +24 silly registry.get cb [ 304, +24 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +24 silly registry.get etag: '"899R1W8XNWSIDYL830UTYNK3T"', +24 silly registry.get date: 'Tue, 29 Jan 2013 16:11:45 GMT', +24 silly registry.get 'content-length': '0' } ] +25 verbose etag browserify from cache +26 silly addNameRange number 2 { name: 'browserify', range: '', hasData: true } +27 silly addNameRange versions [ 'browserify', +27 silly addNameRange [ '0.0.1', +27 silly addNameRange '0.0.2', +27 silly addNameRange '0.0.3', +27 silly addNameRange '0.0.4', +27 silly addNameRange '0.0.5', +27 silly addNameRange '0.1.0', +27 silly addNameRange '0.1.1', +27 silly addNameRange '0.1.2', +27 silly addNameRange '0.1.3', +27 silly addNameRange '0.1.4', +27 silly addNameRange '0.1.5', +27 silly addNameRange '0.2.0', +27 silly addNameRange '0.2.1', +27 silly addNameRange '0.2.2', +27 silly addNameRange '0.2.3', +27 silly addNameRange '0.2.4', +27 silly addNameRange '0.2.5', +27 silly addNameRange '0.2.6', +27 silly addNameRange '0.2.7', +27 silly addNameRange '0.2.8', +27 silly addNameRange '0.2.9', +27 silly addNameRange '0.2.10', +27 silly addNameRange '0.2.11', +27 silly addNameRange '0.3.0', +27 silly addNameRange '0.3.1', +27 silly addNameRange '0.3.2', +27 silly addNameRange '0.3.3', +27 silly addNameRange '0.3.4', +27 silly addNameRange '0.3.5', +27 silly addNameRange '0.3.6', +27 silly addNameRange '0.3.7', +27 silly addNameRange '0.4.0', +27 silly addNameRange '0.4.1', +27 silly addNameRange '0.4.2', +27 silly addNameRange '0.4.3', +27 silly addNameRange '0.4.4', +27 silly addNameRange '0.4.5', +27 silly addNameRange '0.4.6', +27 silly addNameRange '0.4.7', +27 silly addNameRange '0.4.8', +27 silly addNameRange '0.4.9', +27 silly addNameRange '0.4.10', +27 silly addNameRange '0.4.11', +27 silly addNameRange '0.4.12', +27 silly addNameRange '0.4.13', +27 silly addNameRange '0.4.14', +27 silly addNameRange '0.4.15', +27 silly addNameRange '0.5.0', +27 silly addNameRange '0.5.1', +27 silly addNameRange '0.5.2', +27 silly addNameRange '1.0.0', +27 silly addNameRange '1.1.0', +27 silly addNameRange '1.1.1', +27 silly addNameRange '1.1.2', +27 silly addNameRange '1.1.3', +27 silly addNameRange '1.1.4', +27 silly addNameRange '1.2.0', +27 silly addNameRange '1.2.1', +27 silly addNameRange '1.2.2', +27 silly addNameRange '1.2.3', +27 silly addNameRange '1.2.4', +27 silly addNameRange '1.2.5', +27 silly addNameRange '1.2.6', +27 silly addNameRange '1.2.7', +27 silly addNameRange '1.2.8', +27 silly addNameRange '1.2.9', +27 silly addNameRange '1.3.0', +27 silly addNameRange '1.4.0', +27 silly addNameRange '1.4.1', +27 silly addNameRange '1.4.2', +27 silly addNameRange '1.4.3', +27 silly addNameRange '1.4.4', +27 silly addNameRange '1.4.5', +27 silly addNameRange '1.4.6', +27 silly addNameRange '1.4.7', +27 silly addNameRange '1.4.8', +27 silly addNameRange '1.5.0', +27 silly addNameRange '1.6.0', +27 silly addNameRange '1.6.1', +27 silly addNameRange '1.7.0', +27 silly addNameRange '1.7.1', +27 silly addNameRange '1.7.2', +27 silly addNameRange '1.7.3', +27 silly addNameRange '1.7.4', +27 silly addNameRange '1.7.5', +27 silly addNameRange '1.7.6', +27 silly addNameRange '1.7.7', +27 silly addNameRange '1.8.0', +27 silly addNameRange '1.8.1', +27 silly addNameRange '1.8.2', +27 silly addNameRange '1.8.3', +27 silly addNameRange '1.9.0', +27 silly addNameRange '1.9.1', +27 silly addNameRange '1.9.2', +27 silly addNameRange '1.9.3', +27 silly addNameRange '1.9.4', +27 silly addNameRange '1.10.0', +27 silly addNameRange '1.10.1', +27 silly addNameRange '1.10.2', +27 silly addNameRange '1.10.3', +27 silly addNameRange '1.10.4', +27 silly addNameRange '1.10.5', +27 silly addNameRange '1.10.6', +27 silly addNameRange '1.10.7', +27 silly addNameRange '1.10.8', +27 silly addNameRange '1.10.9', +27 silly addNameRange '1.10.11', +27 silly addNameRange '1.10.12', +27 silly addNameRange '1.10.13', +27 silly addNameRange '1.10.14', +27 silly addNameRange '1.10.15', +27 silly addNameRange '1.10.16', +27 silly addNameRange '1.10.17', +27 silly addNameRange '1.11.0', +27 silly addNameRange '1.11.1', +27 silly addNameRange '1.12.0', +27 silly addNameRange '1.12.1', +27 silly addNameRange '1.12.2', +27 silly addNameRange '1.12.3', +27 silly addNameRange '1.13.0', +27 silly addNameRange '1.13.1', +27 silly addNameRange '1.13.2', +27 silly addNameRange '1.13.3', +27 silly addNameRange '1.13.4', +27 silly addNameRange '1.13.5', +27 silly addNameRange '1.13.6', +27 silly addNameRange '1.13.8', +27 silly addNameRange '1.13.9', +27 silly addNameRange '1.13.10', +27 silly addNameRange '1.14.0', +27 silly addNameRange '1.14.1', +27 silly addNameRange '1.14.2', +27 silly addNameRange '1.14.3', +27 silly addNameRange '1.14.4', +27 silly addNameRange '1.14.5', +27 silly addNameRange '1.15.0', +27 silly addNameRange '1.15.1', +27 silly addNameRange '1.15.2', +27 silly addNameRange '1.15.3', +27 silly addNameRange '1.15.4', +27 silly addNameRange '1.15.5', +27 silly addNameRange '1.15.6', +27 silly addNameRange '1.16.0', +27 silly addNameRange '1.16.1', +27 silly addNameRange '1.16.2', +27 silly addNameRange '1.16.3', +27 silly addNameRange '1.16.4', +27 silly addNameRange '1.16.5', +27 silly addNameRange '1.16.6', +27 silly addNameRange '1.16.7', +27 silly addNameRange '1.16.8', +27 silly addNameRange '1.17.0', +27 silly addNameRange '1.17.1', +27 silly addNameRange '1.17.2', +27 silly addNameRange '1.17.3' ] ] +28 verbose addNamed [ 'browserify', '1.17.3' ] +29 verbose addNamed [ '1.17.3', '1.17.3' ] +30 silly lockFile 2c130a86-browserify-1-17-3 [email protected] +31 verbose lock [email protected] /Users/wilsonpage/.npm/2c130a86-browserify-1-17-3.lock +32 verbose read json /Users/wilsonpage/.npm/browserify/1.17.3/package/package.json +33 silly lockFile 2c130a86-browserify-1-17-3 [email protected] +34 silly lockFile 80140245-browserify browserify@ +35 silly resolved [ { name: 'browserify', +35 silly resolved version: '1.17.3', +35 silly resolved description: 'browser-side require() the node way', +35 silly resolved main: 'index.js', +35 silly resolved bin: { browserify: 'bin/cmd.js' }, +35 silly resolved directories: { example: 'example', test: 'test' }, +35 silly resolved repository: +35 silly resolved { type: 'git', +35 silly resolved url: 'http://github.com/substack/node-browserify.git' }, +35 silly resolved keywords: +35 silly resolved [ 'browser', +35 silly resolved 'require', +35 silly resolved 'middleware', +35 silly resolved 'bundle', +35 silly resolved 'npm', +35 silly resolved 'coffee', +35 silly resolved 'javascript' ], +35 silly resolved dependencies: +35 silly resolved { detective: '~0.2.0', +35 silly resolved 'buffer-browserify': '~0.0.1', +35 silly resolved 'console-browserify': '~0.1.0', +35 silly resolved deputy: '~0.0.3', +35 silly resolved 'syntax-error': '~0.0.0', +35 silly resolved resolve: '~0.2.0', +35 silly resolved nub: '~0.0.0', +35 silly resolved commondir: '~0.0.1', +35 silly resolved 'coffee-script': '1.x.x', +35 silly resolved optimist: '~0.3.4', +35 silly resolved 'http-browserify': '~0.1.1', +35 silly resolved 'vm-browserify': '~0.0.0', +35 silly resolved 'crypto-browserify': '~0' }, +35 silly resolved devDependencies: +35 silly resolved { tap: '~0.2.5', +35 silly resolved connect: '1.8.5', +35 silly resolved hashish: '>=0.0.2 <0.1', +35 silly resolved traverse: '>=0.3.8 <0.4', +35 silly resolved backbone: '~0.9.2', +35 silly resolved dnode: '~0.9.11', +35 silly resolved jade: '0.20.0', +35 silly resolved seq: '0.3.3', +35 silly resolved 'jquery-browserify': '*', +35 silly resolved lazy: '1.0.x', +35 silly resolved ecstatic: '~0.1.4', +35 silly resolved mkdirp: '~0.3.3' }, +35 silly resolved author: +35 silly resolved { name: 'James Halliday', +35 silly resolved email: '[email protected]', +35 silly resolved url: 'http://substack.net' }, +35 silly resolved scripts: { test: 'node node_modules/tap/bin/tap.js test/*.js' }, +35 silly resolved license: 'MIT/X11', +35 silly resolved engine: { node: '>=0.6.0' }, +35 silly resolved readme: 'browserify\n==========\n\nMake node-style require() work in the browser with a server-side build step,\nas if by magic!\n\n[](http://travis-ci.org/substack/node-browserify)\n\n\n\nexample\n=======\n\nJust write an `entry.js` to start with some `require()`s in it:\n\n````javascript\n// use relative requires\nvar foo = require(\'./foo\');\nvar bar = require(\'../lib/bar\');\n\n// or use modules installed by npm into node_modules/\nvar gamma = require(\'gamma\');\n\nvar elem = document.getElementById(\'result\');\nvar x = foo(100) + bar(\'baz\');\nelem.textContent = gamma(x);\n````\n\nNow just use the `browserify` command to build a bundle starting at `entry.js`:\n\n```\n$ browserify entry.js -o bundle.js\n```\n\nAll of the modules that `entry.js` needs are included in the final bundle from a\nrecursive walk using [detective](https://github.com/substack/node-detective).\n\nTo use the bundle, just toss a `<script src="bundle.js"></script>` into your\nhtml!\n\nusage\n=====\n\n````\nUsage: browserify [entry files] {OPTIONS}\n\nOptions:\n --outfile, -o Write the browserify bundle to this file.\n If unspecified, browserify prints to stdout. \n --require, -r A module name or file to bundle.require()\n Optionally use a colon separator to set the target. \n --entry, -e An entry point of your app \n --exports Export these core objects, comma-separated list\n with any of: require, process. If unspecified, the\n export behavior will be inferred.\n \n --ignore, -i Ignore a file \n --alias, -a Register an alias with a colon separator: "to:from"\n Example: --alias \'jquery:jquery-browserify\' \n --cache, -c Turn on caching at $HOME/.config/browserling/cache.json or use\n a file for caching.\n [default: true]\n --debug, -d Switch on debugging mode with //@ sourceURL=...s. [boolean]\n --plugin, -p Use a plugin.\n Example: --plugin aliasify \n --prelude Include the code that defines require() in this bundle.\n [boolean] [default: true]\n --watch, -w Watch for changes. The script will stay open and write updates\n to the output every time any of the bundled files change.\n This option only works in tandem with -o. \n --verbose, -v Write out how many bytes were written in -o mode. This is\n especially useful with --watch. \n --help, -h Show this message \n\n````\n\ncompatibility\n=============\n\nMany [npm](http://npmjs.org) modules that don\'t do IO will just work after being\nbrowserified. Others take more work.\n\n[coffee script](http://coffeescript.org/) should pretty much just work.\nJust do `browserify entry.coffee` or `require(\'./foo.coffee\')`.\n\nMany node built-in modules have been wrapped to work in the browser.\nAll you need to do is `require()` them like in node.\n\n* events\n* path\n* [vm](https://github.com/substack/vm-browserify)\n* [http](https://github.com/substack/http-browserify)\n* [crypto](https://github.com/dominictarr/crypto-browserify)\n* assert\n* url\n* buffer\n* buffer_ieee754\n* util\n* querystring\n* stream\n\nprocess\n-------\n\nBrowserify makes available a faux `process` object to modules with these\nattributes:\n\n* nextTick(fn) - uses [the postMessage trick](http://dbaron.org/log/20100309-faster-timeouts)\n for a faster `setTimeout(fn, 0)` if it can\n* title - set to \'browser\' for browser code, \'node\' in regular node code\n* browser - `true`, good for testing if you\'re in a browser or in node\n\nBy default the process object is only available inside of files wrapped by\nbrowserify. To expose it, use `--exports=process`\n\n__dirname\n---------\n\nThe faux directory name, scrubbed of true directory information so as not to\nexpose your filesystem organization.\n\n__filename\n----------\n\nThe faux file path, scrubbed of true path information so as not to expose your\nfilesystem organization.\n\npackage.json\n============\n\nIn order to resolve main files for projects, the package.json "main" field is\nread.\n\nIf a package.json has a "browserify" field, you can override the standard "main"\nbehavior with something special just for browsers.\n\nSee [dnode\'s\npackage.json](https://github.com/substack/dnode/blob/9e24b97cf2ce931fbf6d7beb3731086b46bca887/package.json#L40)\nfor an example of using the "browserify" field.\n\nmore\n====\n\n* [browserify recipes](https://github.com/substack/node-browserify/blob/master/doc/recipes.markdown#recipes)\n* [browserify api reference](https://github.com/substack/node-browserify/blob/master/doc/methods.markdown#methods)\n* [browserify cdn](http://browserify.nodejitsu.com/)\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install -g browserify\n```\n\ntest\n====\n\nTo run the node tests with tap, do:\n\n```\nnpm test\n```\n\nTo run the [testling](http://testling.com) tests,\ncreate a [browserling](http://browserling.com) account then:\n\n```\ncd testling\n./test.sh\n```\n', +35 silly resolved readmeFilename: 'README.markdown', +35 silly resolved _id: '[email protected]', +35 silly resolved _from: 'browserify@' } ] +36 info install [email protected] into /usr/local/lib +37 info installOne [email protected] +38 verbose from cache /Users/wilsonpage/.npm/browserify/1.17.3/package/package.json +39 info /usr/local/lib/node_modules/browserify unbuild +40 verbose read json /usr/local/lib/node_modules/browserify/package.json +41 verbose tar unpack /Users/wilsonpage/.npm/browserify/1.17.3/package.tgz +42 silly lockFile 361ec04d-ocal-lib-node-modules-browserify /usr/local/lib/node_modules/browserify +43 verbose lock /usr/local/lib/node_modules/browserify /Users/wilsonpage/.npm/361ec04d-ocal-lib-node-modules-browserify.lock +44 silly gunzTarPerm modes [ '755', '644' ] +45 silly gunzTarPerm extractEntry package.json +46 silly gunzTarPerm extractEntry LICENSE +47 silly gunzTarPerm extractEntry index.js +48 silly gunzTarPerm extractEntry doc/methods.markdown +49 silly gunzTarPerm extractEntry doc/recipes.markdown +50 silly gunzTarPerm extractEntry example/debug/browserify.js +51 silly gunzTarPerm extractEntry example/debug/server.js +52 silly gunzTarPerm extractEntry example/debug/build.sh +53 silly gunzTarPerm extractEntry example/debug/index.html +54 silly gunzTarPerm extractEntry example/debug/js/entry.js +55 silly gunzTarPerm extractEntry example/debug/js/thrower.js +56 silly gunzTarPerm extractEntry example/simple-build/browserify.js +57 silly gunzTarPerm extractEntry example/simple-build/server.js +58 silly gunzTarPerm extractEntry example/simple-build/build.sh +59 silly gunzTarPerm extractEntry example/simple-build/index.html +60 silly gunzTarPerm extractEntry example/simple-build/js/bar.js +61 silly gunzTarPerm extractEntry example/simple-build/js/entry.js +62 silly gunzTarPerm extractEntry example/simple-build/js/foo.js +63 silly gunzTarPerm extractEntry example/test/b.js +64 silly gunzTarPerm extractEntry example/test/bar.js +65 silly gunzTarPerm extractEntry example/test/foo.js +66 silly gunzTarPerm extractEntry example/test/m.js +67 silly gunzTarPerm extractEntry example/test/n.js +68 silly gunzTarPerm extractEntry example/using-http/bundle.js +69 silly gunzTarPerm extractEntry example/using-http/entry.js +70 silly gunzTarPerm extractEntry example/using-http/server.js +71 silly gunzTarPerm extractEntry example/using-http/index.html +72 silly gunzTarPerm extractEntry .travis.yml +73 silly gunzTarPerm extractEntry lib/watch.js +74 silly gunzTarPerm extractEntry lib/wrap.js +75 silly gunzTarPerm extractEntry lib/wrappers.js +76 silly gunzTarPerm extractEntry bin/cmd.js +77 silly gunzTarPerm extractEntry builtins/__browserify_process.js +78 silly gunzTarPerm extractEntry builtins/https.js +79 silly gunzTarPerm extractEntry builtins/net.js +80 silly gunzTarPerm extractEntry builtins/path.js +81 silly gunzTarPerm extractEntry builtins/fs.js +82 silly gunzTarPerm extractEntry builtins/stream.js +83 silly gunzTarPerm extractEntry builtins/string_decoder.js +84 silly gunzTarPerm extractEntry builtins/sys.js +85 silly gunzTarPerm extractEntry builtins/timers.js +86 silly gunzTarPerm extractEntry builtins/tls.js +87 silly gunzTarPerm extractEntry builtins/events.js +88 silly gunzTarPerm extractEntry builtins/tty.js +89 silly gunzTarPerm extractEntry builtins/child_process.js +90 silly gunzTarPerm extractEntry builtins/url.js +91 silly gunzTarPerm extractEntry builtins/assert.js +92 silly gunzTarPerm extractEntry builtins/util.js +93 silly gunzTarPerm extractEntry builtins/querystring.js +94 silly gunzTarPerm extractEntry README.markdown +95 silly gunzTarPerm extractEntry test/alias.js +96 silly gunzTarPerm extractEntry test/dnode.js +97 silly gunzTarPerm extractEntry test/subdep.js +98 silly gunzTarPerm extractEntry test/dollar.js +99 silly gunzTarPerm extractEntry test/crypto.js +100 silly gunzTarPerm extractEntry test/entry.js +101 silly gunzTarPerm extractEntry test/retarget.js +102 silly gunzTarPerm extractEntry test/error_code.js +103 silly gunzTarPerm extractEntry test/require_cache.js +104 silly gunzTarPerm extractEntry test/export.js +105 silly gunzTarPerm extractEntry test/comment.js +106 silly gunzTarPerm extractEntry test/multi_ignore.js +107 silly gunzTarPerm extractEntry test/util.js +108 silly gunzTarPerm extractEntry test/backbone.js +109 silly gunzTarPerm extractEntry test/coffee.js +110 silly gunzTarPerm extractEntry test/multi_entry.js +111 silly gunzTarPerm extractEntry test/watch.js +112 silly gunzTarPerm extractEntry test/global.js +113 silly gunzTarPerm extractEntry test/cache.js +114 silly gunzTarPerm extractEntry test/jade.js +115 silly gunzTarPerm extractEntry test/bundle.js +116 silly gunzTarPerm extractEntry test/module.js +117 silly gunzTarPerm extractEntry test/buffer.js +118 silly gunzTarPerm extractEntry test/json.js +119 silly gunzTarPerm extractEntry test/bin.js +120 silly gunzTarPerm extractEntry test/maxlisteners.js +121 silly gunzTarPerm extractEntry test/seq.js +122 silly gunzTarPerm extractEntry test/wrap.js +123 silly gunzTarPerm extractEntry test/field.js +124 silly gunzTarPerm extractEntry test/json/main.js +125 silly gunzTarPerm extractEntry test/json/beep.json +126 silly gunzTarPerm extractEntry test/global/main.js +127 silly gunzTarPerm extractEntry test/field/miss.js +128 silly gunzTarPerm extractEntry test/field/object.js +129 silly gunzTarPerm extractEntry test/field/string.js +130 silly gunzTarPerm extractEntry test/field/sub.js +131 silly gunzTarPerm extractEntry test/field/node_modules/z-miss/package.json +132 silly gunzTarPerm extractEntry test/field/node_modules/z-miss/browser.js +133 silly gunzTarPerm extractEntry test/field/node_modules/z-miss/main.js +134 silly gunzTarPerm extractEntry test/field/node_modules/z-object/package.json +135 silly gunzTarPerm extractEntry test/field/node_modules/z-object/browser.js +136 silly gunzTarPerm extractEntry test/field/node_modules/z-object/main.js +137 silly gunzTarPerm extractEntry test/field/node_modules/z-string/package.json +138 silly gunzTarPerm extractEntry test/field/node_modules/z-string/browser.js +139 silly gunzTarPerm extractEntry test/field/node_modules/z-string/main.js +140 silly gunzTarPerm extractEntry test/field/node_modules/z-sub/package.json +141 silly gunzTarPerm extractEntry test/field/node_modules/z-sub/main.js +142 silly gunzTarPerm extractEntry test/field/node_modules/z-sub/browser/a.js +143 silly gunzTarPerm extractEntry test/field/node_modules/z-sub/browser/b.js +144 silly gunzTarPerm extractEntry test/wrap/a.js +145 silly gunzTarPerm extractEntry test/wrap/c.js +146 silly gunzTarPerm extractEntry test/wrap/skipme.js +147 silly gunzTarPerm extractEntry test/wrap/x.js +148 silly gunzTarPerm extractEntry test/wrap/node_modules/b/package.json +149 silly gunzTarPerm extractEntry test/wrap/node_modules/b/main.js +150 silly gunzTarPerm extractEntry test/wrap/node_modules/skipmetoo/index.js +151 silly gunzTarPerm extractEntry test/export/entry.js +152 silly gunzTarPerm extractEntry test/error_code/src.js +153 silly gunzTarPerm extractEntry test/multi_entry/a.js +154 silly gunzTarPerm extractEntry test/multi_entry/b.js +155 silly gunzTarPerm extractEntry test/multi_entry/c.js +156 silly gunzTarPerm extractEntry test/subdep/package.json +157 silly gunzTarPerm extractEntry test/subdep/index.js +158 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/package.json +159 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/b.js +160 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/ignore_me.js +161 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/a/package.json +162 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/a/index.js +163 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/c/package.json +164 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/c/index.js +165 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/f/index.js +166 silly gunzTarPerm extractEntry test/subdep/node_modules/qq/node_modules/z/index.js +167 silly gunzTarPerm extractEntry test/dollar/dollar/index.js +168 silly gunzTarPerm extractEntry test/comment/main.js +169 silly gunzTarPerm extractEntry test/watch/a.js +170 silly gunzTarPerm extractEntry test/coffee/bar.js +171 silly gunzTarPerm extractEntry test/coffee/baz.coffee +172 silly gunzTarPerm extractEntry test/coffee/entry.coffee +173 silly gunzTarPerm extractEntry test/coffee/foo.coffee +174 silly gunzTarPerm extractEntry test/coffee/index.coffee +175 silly gunzTarPerm extractEntry test/coffee/nested/nested.coffee +176 silly gunzTarPerm extractEntry test/entry/main.js +177 silly gunzTarPerm extractEntry test/entry/one.js +178 silly gunzTarPerm extractEntry test/entry/two.js +179 silly gunzTarPerm extractEntry test/node_modules/beep/index.js +180 silly gunzTarPerm extractEntry testling/tick.js +181 silly gunzTarPerm extractEntry testling/timers.js +182 silly gunzTarPerm extractEntry testling/util.js +183 silly gunzTarPerm extractEntry testling/README.markdown +184 silly gunzTarPerm extractEntry testling/test.sh +185 silly gunzTarPerm extractEntry v2.markdown +186 silly gunzTarPerm extractEntry wrappers/alias.js +187 silly gunzTarPerm extractEntry wrappers/body.js +188 silly gunzTarPerm extractEntry wrappers/body_debug.js +189 silly gunzTarPerm extractEntry wrappers/entry.js +190 silly gunzTarPerm extractEntry wrappers/entry_debug.js +191 silly gunzTarPerm extractEntry wrappers/package.js +192 silly gunzTarPerm extractEntry wrappers/prelude.js +193 verbose read json /usr/local/lib/node_modules/browserify/package.json +194 silly lockFile 361ec04d-ocal-lib-node-modules-browserify /usr/local/lib/node_modules/browserify +195 info preinstall [email protected] +196 verbose from cache /usr/local/lib/node_modules/browserify/package.json +197 verbose readDependencies using package.json deps +198 verbose from cache /usr/local/lib/node_modules/browserify/package.json +199 verbose readDependencies using package.json deps +200 verbose cache add [ 'detective@~0.2.0', null ] +201 verbose cache add name=undefined spec="detective@~0.2.0" args=["detective@~0.2.0",null] +202 verbose parsed url { pathname: 'detective@~0.2.0', +202 verbose parsed url path: 'detective@~0.2.0', +202 verbose parsed url href: 'detective@~0.2.0' } +203 verbose cache add name="detective" spec="~0.2.0" args=["detective","~0.2.0"] +204 verbose parsed url { pathname: '~0.2.0', path: '~0.2.0', href: '~0.2.0' } +205 verbose addNamed [ 'detective', '~0.2.0' ] +206 verbose addNamed [ null, '>=0.2.0- <0.3.0-' ] +207 silly lockFile 7bc3123d-detective-0-2-0 detective@~0.2.0 +208 verbose lock detective@~0.2.0 /Users/wilsonpage/.npm/7bc3123d-detective-0-2-0.lock +209 verbose cache add [ 'buffer-browserify@~0.0.1', null ] +210 verbose cache add name=undefined spec="buffer-browserify@~0.0.1" args=["buffer-browserify@~0.0.1",null] +211 verbose parsed url { pathname: 'buffer-browserify@~0.0.1', +211 verbose parsed url path: 'buffer-browserify@~0.0.1', +211 verbose parsed url href: 'buffer-browserify@~0.0.1' } +212 verbose cache add name="buffer-browserify" spec="~0.0.1" args=["buffer-browserify","~0.0.1"] +213 verbose parsed url { pathname: '~0.0.1', path: '~0.0.1', href: '~0.0.1' } +214 verbose addNamed [ 'buffer-browserify', '~0.0.1' ] +215 verbose addNamed [ null, '>=0.0.1- <0.1.0-' ] +216 silly lockFile 079b8dc8-buffer-browserify-0-0-1 buffer-browserify@~0.0.1 +217 verbose lock buffer-browserify@~0.0.1 /Users/wilsonpage/.npm/079b8dc8-buffer-browserify-0-0-1.lock +218 silly addNameRange { name: 'detective', range: '>=0.2.0- <0.3.0-', hasData: false } +219 silly addNameRange { name: 'buffer-browserify', +219 silly addNameRange range: '>=0.0.1- <0.1.0-', +219 silly addNameRange hasData: false } +220 verbose url raw detective +221 verbose url resolving [ 'https://registry.npmjs.org/', './detective' ] +222 verbose url resolved https://registry.npmjs.org/detective +223 info trying registry request attempt 1 at 16:13:26 +224 verbose etag "CS22IULIINICISVA17X1DZX9H" +225 http GET https://registry.npmjs.org/detective +226 verbose url raw buffer-browserify +227 verbose url resolving [ 'https://registry.npmjs.org/', './buffer-browserify' ] +228 verbose url resolved https://registry.npmjs.org/buffer-browserify +229 info trying registry request attempt 1 at 16:13:26 +230 verbose etag "4QNNANHHHCTJCSSXMTEBKT9PH" +231 http GET https://registry.npmjs.org/buffer-browserify +232 verbose cache add [ 'console-browserify@~0.1.0', null ] +233 verbose cache add name=undefined spec="console-browserify@~0.1.0" args=["console-browserify@~0.1.0",null] +234 verbose parsed url { pathname: 'console-browserify@~0.1.0', +234 verbose parsed url path: 'console-browserify@~0.1.0', +234 verbose parsed url href: 'console-browserify@~0.1.0' } +235 verbose cache add name="console-browserify" spec="~0.1.0" args=["console-browserify","~0.1.0"] +236 verbose parsed url { pathname: '~0.1.0', path: '~0.1.0', href: '~0.1.0' } +237 verbose addNamed [ 'console-browserify', '~0.1.0' ] +238 verbose addNamed [ null, '>=0.1.0- <0.2.0-' ] +239 silly lockFile abfcf364-console-browserify-0-1-0 console-browserify@~0.1.0 +240 verbose lock console-browserify@~0.1.0 /Users/wilsonpage/.npm/abfcf364-console-browserify-0-1-0.lock +241 verbose cache add [ 'deputy@~0.0.3', null ] +242 verbose cache add name=undefined spec="deputy@~0.0.3" args=["deputy@~0.0.3",null] +243 verbose parsed url { pathname: 'deputy@~0.0.3', +243 verbose parsed url path: 'deputy@~0.0.3', +243 verbose parsed url href: 'deputy@~0.0.3' } +244 verbose cache add name="deputy" spec="~0.0.3" args=["deputy","~0.0.3"] +245 verbose parsed url { pathname: '~0.0.3', path: '~0.0.3', href: '~0.0.3' } +246 verbose addNamed [ 'deputy', '~0.0.3' ] +247 verbose addNamed [ null, '>=0.0.3- <0.1.0-' ] +248 silly lockFile f65dca98-deputy-0-0-3 deputy@~0.0.3 +249 verbose lock deputy@~0.0.3 /Users/wilsonpage/.npm/f65dca98-deputy-0-0-3.lock +250 verbose cache add [ 'syntax-error@~0.0.0', null ] +251 verbose cache add name=undefined spec="syntax-error@~0.0.0" args=["syntax-error@~0.0.0",null] +252 verbose parsed url { pathname: 'syntax-error@~0.0.0', +252 verbose parsed url path: 'syntax-error@~0.0.0', +252 verbose parsed url href: 'syntax-error@~0.0.0' } +253 verbose cache add name="syntax-error" spec="~0.0.0" args=["syntax-error","~0.0.0"] +254 verbose parsed url { pathname: '~0.0.0', path: '~0.0.0', href: '~0.0.0' } +255 verbose addNamed [ 'syntax-error', '~0.0.0' ] +256 verbose addNamed [ null, '>=0.0.0- <0.1.0-' ] +257 silly lockFile 541c7056-syntax-error-0-0-0 syntax-error@~0.0.0 +258 verbose lock syntax-error@~0.0.0 /Users/wilsonpage/.npm/541c7056-syntax-error-0-0-0.lock +259 verbose cache add [ 'resolve@~0.2.0', null ] +260 verbose cache add name=undefined spec="resolve@~0.2.0" args=["resolve@~0.2.0",null] +261 verbose parsed url { pathname: 'resolve@~0.2.0', +261 verbose parsed url path: 'resolve@~0.2.0', +261 verbose parsed url href: 'resolve@~0.2.0' } +262 verbose cache add name="resolve" spec="~0.2.0" args=["resolve","~0.2.0"] +263 verbose parsed url { pathname: '~0.2.0', path: '~0.2.0', href: '~0.2.0' } +264 verbose addNamed [ 'resolve', '~0.2.0' ] +265 verbose addNamed [ null, '>=0.2.0- <0.3.0-' ] +266 silly lockFile eb1ed680-resolve-0-2-0 resolve@~0.2.0 +267 verbose lock resolve@~0.2.0 /Users/wilsonpage/.npm/eb1ed680-resolve-0-2-0.lock +268 verbose cache add [ 'nub@~0.0.0', null ] +269 verbose cache add name=undefined spec="nub@~0.0.0" args=["nub@~0.0.0",null] +270 verbose parsed url { pathname: 'nub@~0.0.0', +270 verbose parsed url path: 'nub@~0.0.0', +270 verbose parsed url href: 'nub@~0.0.0' } +271 verbose cache add name="nub" spec="~0.0.0" args=["nub","~0.0.0"] +272 verbose parsed url { pathname: '~0.0.0', path: '~0.0.0', href: '~0.0.0' } +273 verbose addNamed [ 'nub', '~0.0.0' ] +274 verbose addNamed [ null, '>=0.0.0- <0.1.0-' ] +275 silly lockFile fe411909-nub-0-0-0 nub@~0.0.0 +276 verbose lock nub@~0.0.0 /Users/wilsonpage/.npm/fe411909-nub-0-0-0.lock +277 verbose cache add [ 'commondir@~0.0.1', null ] +278 verbose cache add name=undefined spec="commondir@~0.0.1" args=["commondir@~0.0.1",null] +279 verbose parsed url { pathname: 'commondir@~0.0.1', +279 verbose parsed url path: 'commondir@~0.0.1', +279 verbose parsed url href: 'commondir@~0.0.1' } +280 verbose cache add name="commondir" spec="~0.0.1" args=["commondir","~0.0.1"] +281 verbose parsed url { pathname: '~0.0.1', path: '~0.0.1', href: '~0.0.1' } +282 verbose addNamed [ 'commondir', '~0.0.1' ] +283 verbose addNamed [ null, '>=0.0.1- <0.1.0-' ] +284 silly lockFile d18c18a5-commondir-0-0-1 commondir@~0.0.1 +285 verbose lock commondir@~0.0.1 /Users/wilsonpage/.npm/d18c18a5-commondir-0-0-1.lock +286 verbose cache add [ '[email protected]', null ] +287 verbose cache add name=undefined spec="[email protected]" args=["[email protected]",null] +288 verbose parsed url { pathname: '[email protected]', +288 verbose parsed url path: '[email protected]', +288 verbose parsed url href: '[email protected]' } +289 verbose cache add name="coffee-script" spec="1.x.x" args=["coffee-script","1.x.x"] +290 verbose parsed url { pathname: '1.x.x', path: '1.x.x', href: '1.x.x' } +291 verbose addNamed [ 'coffee-script', '1.x.x' ] +292 verbose addNamed [ null, '>=1.0.0- <2.0.0-' ] +293 silly lockFile edf96972-coffee-script-1-x-x [email protected] +294 verbose lock [email protected] /Users/wilsonpage/.npm/edf96972-coffee-script-1-x-x.lock +295 verbose cache add [ 'optimist@~0.3.4', null ] +296 verbose cache add name=undefined spec="optimist@~0.3.4" args=["optimist@~0.3.4",null] +297 verbose parsed url { pathname: 'optimist@~0.3.4', +297 verbose parsed url path: 'optimist@~0.3.4', +297 verbose parsed url href: 'optimist@~0.3.4' } +298 verbose cache add name="optimist" spec="~0.3.4" args=["optimist","~0.3.4"] +299 verbose parsed url { pathname: '~0.3.4', path: '~0.3.4', href: '~0.3.4' } +300 verbose addNamed [ 'optimist', '~0.3.4' ] +301 verbose addNamed [ null, '>=0.3.4- <0.4.0-' ] +302 silly lockFile 094c60bd-optimist-0-3-4 optimist@~0.3.4 +303 verbose lock optimist@~0.3.4 /Users/wilsonpage/.npm/094c60bd-optimist-0-3-4.lock +304 verbose cache add [ 'http-browserify@~0.1.1', null ] +305 verbose cache add name=undefined spec="http-browserify@~0.1.1" args=["http-browserify@~0.1.1",null] +306 verbose parsed url { pathname: 'http-browserify@~0.1.1', +306 verbose parsed url path: 'http-browserify@~0.1.1', +306 verbose parsed url href: 'http-browserify@~0.1.1' } +307 verbose cache add name="http-browserify" spec="~0.1.1" args=["http-browserify","~0.1.1"] +308 verbose parsed url { pathname: '~0.1.1', path: '~0.1.1', href: '~0.1.1' } +309 verbose addNamed [ 'http-browserify', '~0.1.1' ] +310 verbose addNamed [ null, '>=0.1.1- <0.2.0-' ] +311 silly lockFile 83e61da6-http-browserify-0-1-1 http-browserify@~0.1.1 +312 verbose lock http-browserify@~0.1.1 /Users/wilsonpage/.npm/83e61da6-http-browserify-0-1-1.lock +313 verbose cache add [ 'vm-browserify@~0.0.0', null ] +314 verbose cache add name=undefined spec="vm-browserify@~0.0.0" args=["vm-browserify@~0.0.0",null] +315 verbose parsed url { pathname: 'vm-browserify@~0.0.0', +315 verbose parsed url path: 'vm-browserify@~0.0.0', +315 verbose parsed url href: 'vm-browserify@~0.0.0' } +316 verbose cache add name="vm-browserify" spec="~0.0.0" args=["vm-browserify","~0.0.0"] +317 verbose parsed url { pathname: '~0.0.0', path: '~0.0.0', href: '~0.0.0' } +318 verbose addNamed [ 'vm-browserify', '~0.0.0' ] +319 verbose addNamed [ null, '>=0.0.0- <0.1.0-' ] +320 silly lockFile 29145f01-vm-browserify-0-0-0 vm-browserify@~0.0.0 +321 verbose lock vm-browserify@~0.0.0 /Users/wilsonpage/.npm/29145f01-vm-browserify-0-0-0.lock +322 verbose cache add [ 'crypto-browserify@~0', null ] +323 verbose cache add name=undefined spec="crypto-browserify@~0" args=["crypto-browserify@~0",null] +324 verbose parsed url { pathname: 'crypto-browserify@~0', +324 verbose parsed url path: 'crypto-browserify@~0', +324 verbose parsed url href: 'crypto-browserify@~0' } +325 verbose cache add name="crypto-browserify" spec="~0" args=["crypto-browserify","~0"] +326 verbose parsed url { pathname: '~0', path: '~0', href: '~0' } +327 verbose addNamed [ 'crypto-browserify', '~0' ] +328 verbose addNamed [ null, '>=0.0.0- <1.0.0-' ] +329 silly lockFile e9cc4b31-crypto-browserify-0 crypto-browserify@~0 +330 verbose lock crypto-browserify@~0 /Users/wilsonpage/.npm/e9cc4b31-crypto-browserify-0.lock +331 silly addNameRange { name: 'console-browserify', +331 silly addNameRange range: '>=0.1.0- <0.2.0-', +331 silly addNameRange hasData: false } +332 silly addNameRange { name: 'deputy', range: '>=0.0.3- <0.1.0-', hasData: false } +333 silly addNameRange { name: 'syntax-error', +333 silly addNameRange range: '>=0.0.0- <0.1.0-', +333 silly addNameRange hasData: false } +334 silly addNameRange { name: 'resolve', range: '>=0.2.0- <0.3.0-', hasData: false } +335 silly addNameRange { name: 'nub', range: '>=0.0.0- <0.1.0-', hasData: false } +336 silly addNameRange { name: 'commondir', range: '>=0.0.1- <0.1.0-', hasData: false } +337 silly addNameRange { name: 'coffee-script', +337 silly addNameRange range: '>=1.0.0- <2.0.0-', +337 silly addNameRange hasData: false } +338 silly addNameRange { name: 'optimist', range: '>=0.3.4- <0.4.0-', hasData: false } +339 silly addNameRange { name: 'http-browserify', +339 silly addNameRange range: '>=0.1.1- <0.2.0-', +339 silly addNameRange hasData: false } +340 silly addNameRange { name: 'vm-browserify', +340 silly addNameRange range: '>=0.0.0- <0.1.0-', +340 silly addNameRange hasData: false } +341 silly addNameRange { name: 'crypto-browserify', +341 silly addNameRange range: '>=0.0.0- <1.0.0-', +341 silly addNameRange hasData: false } +342 verbose url raw console-browserify +343 verbose url resolving [ 'https://registry.npmjs.org/', './console-browserify' ] +344 verbose url resolved https://registry.npmjs.org/console-browserify +345 info trying registry request attempt 1 at 16:13:26 +346 verbose etag "8NQSFR1VJGC9HB5C7AJIIZELT" +347 http GET https://registry.npmjs.org/console-browserify +348 verbose url raw deputy +349 verbose url resolving [ 'https://registry.npmjs.org/', './deputy' ] +350 verbose url resolved https://registry.npmjs.org/deputy +351 info trying registry request attempt 1 at 16:13:26 +352 verbose etag "4AOH7BGC316WGXVN9EL31OZ93" +353 http GET https://registry.npmjs.org/deputy +354 verbose url raw syntax-error +355 verbose url resolving [ 'https://registry.npmjs.org/', './syntax-error' ] +356 verbose url resolved https://registry.npmjs.org/syntax-error +357 info trying registry request attempt 1 at 16:13:26 +358 verbose etag "4T9O90M0FDSNQV970DTCW6MZ9" +359 http GET https://registry.npmjs.org/syntax-error +360 verbose url raw resolve +361 verbose url resolving [ 'https://registry.npmjs.org/', './resolve' ] +362 verbose url resolved https://registry.npmjs.org/resolve +363 info trying registry request attempt 1 at 16:13:26 +364 verbose etag "1PRD1ZSWQFUUV9QIHA7G137QL" +365 http GET https://registry.npmjs.org/resolve +366 verbose url raw nub +367 verbose url resolving [ 'https://registry.npmjs.org/', './nub' ] +368 verbose url resolved https://registry.npmjs.org/nub +369 info trying registry request attempt 1 at 16:13:26 +370 verbose etag "13K3EU4M2PX1SLZHKRRYKF3RR" +371 http GET https://registry.npmjs.org/nub +372 verbose url raw commondir +373 verbose url resolving [ 'https://registry.npmjs.org/', './commondir' ] +374 verbose url resolved https://registry.npmjs.org/commondir +375 info trying registry request attempt 1 at 16:13:26 +376 verbose etag "CBLBPLAJ0K8OBJ8W72IANIRND" +377 http GET https://registry.npmjs.org/commondir +378 verbose url raw coffee-script +379 verbose url resolving [ 'https://registry.npmjs.org/', './coffee-script' ] +380 verbose url resolved https://registry.npmjs.org/coffee-script +381 info trying registry request attempt 1 at 16:13:26 +382 verbose etag "5DVQS1LWDXJKMR2BFTU1OGKFH" +383 http GET https://registry.npmjs.org/coffee-script +384 verbose url raw optimist +385 verbose url resolving [ 'https://registry.npmjs.org/', './optimist' ] +386 verbose url resolved https://registry.npmjs.org/optimist +387 info trying registry request attempt 1 at 16:13:26 +388 verbose etag "EH1DT6319Y8YFU4ST3I7HOF8V" +389 http GET https://registry.npmjs.org/optimist +390 verbose url raw http-browserify +391 verbose url resolving [ 'https://registry.npmjs.org/', './http-browserify' ] +392 verbose url resolved https://registry.npmjs.org/http-browserify +393 info trying registry request attempt 1 at 16:13:26 +394 verbose etag "3ZSAXT2SH4DEHT45GPONPV899" +395 http GET https://registry.npmjs.org/http-browserify +396 verbose url raw vm-browserify +397 verbose url resolving [ 'https://registry.npmjs.org/', './vm-browserify' ] +398 verbose url resolved https://registry.npmjs.org/vm-browserify +399 info trying registry request attempt 1 at 16:13:26 +400 verbose etag "2XG3HQ3T4VY572CS9AFY94WQU" +401 http GET https://registry.npmjs.org/vm-browserify +402 verbose url raw crypto-browserify +403 verbose url resolving [ 'https://registry.npmjs.org/', './crypto-browserify' ] +404 verbose url resolved https://registry.npmjs.org/crypto-browserify +405 info trying registry request attempt 1 at 16:13:26 +406 verbose etag "1MSPD2DY9YO38O07CEG61QQT0" +407 http GET https://registry.npmjs.org/crypto-browserify +408 http 304 https://registry.npmjs.org/detective +409 silly registry.get cb [ 304, +409 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +409 silly registry.get etag: '"CS22IULIINICISVA17X1DZX9H"', +409 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +409 silly registry.get 'content-length': '0' } ] +410 verbose etag detective from cache +411 http 304 https://registry.npmjs.org/buffer-browserify +412 silly registry.get cb [ 304, +412 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +412 silly registry.get etag: '"4QNNANHHHCTJCSSXMTEBKT9PH"', +412 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +412 silly registry.get 'content-length': '0' } ] +413 verbose etag buffer-browserify from cache +414 silly addNameRange number 2 { name: 'detective', range: '>=0.2.0- <0.3.0-', hasData: true } +415 silly addNameRange versions [ 'detective', +415 silly addNameRange [ '0.0.0', +415 silly addNameRange '0.0.1', +415 silly addNameRange '0.0.2', +415 silly addNameRange '0.0.3', +415 silly addNameRange '0.0.4', +415 silly addNameRange '0.1.0', +415 silly addNameRange '0.1.1', +415 silly addNameRange '0.2.0', +415 silly addNameRange '0.2.1' ] ] +416 verbose addNamed [ 'detective', '0.2.1' ] +417 verbose addNamed [ '0.2.1', '0.2.1' ] +418 silly lockFile 1ea47442-detective-0-2-1 [email protected] +419 verbose lock [email protected] /Users/wilsonpage/.npm/1ea47442-detective-0-2-1.lock +420 silly addNameRange number 2 { name: 'buffer-browserify', +420 silly addNameRange range: '>=0.0.1- <0.1.0-', +420 silly addNameRange hasData: true } +421 silly addNameRange versions [ 'buffer-browserify', [ '0.0.1', '0.0.2', '0.0.3', '0.0.4' ] ] +422 verbose addNamed [ 'buffer-browserify', '0.0.4' ] +423 verbose addNamed [ '0.0.4', '0.0.4' ] +424 silly lockFile c0fe6422-buffer-browserify-0-0-4 [email protected] +425 verbose lock [email protected] /Users/wilsonpage/.npm/c0fe6422-buffer-browserify-0-0-4.lock +426 verbose read json /Users/wilsonpage/.npm/detective/0.2.1/package/package.json +427 verbose read json /Users/wilsonpage/.npm/buffer-browserify/0.0.4/package/package.json +428 silly lockFile 1ea47442-detective-0-2-1 [email protected] +429 silly lockFile c0fe6422-buffer-browserify-0-0-4 [email protected] +430 silly lockFile 7bc3123d-detective-0-2-0 detective@~0.2.0 +431 silly lockFile 079b8dc8-buffer-browserify-0-0-1 buffer-browserify@~0.0.1 +432 http 304 https://registry.npmjs.org/console-browserify +433 silly registry.get cb [ 304, +433 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +433 silly registry.get etag: '"8NQSFR1VJGC9HB5C7AJIIZELT"', +433 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +433 silly registry.get 'content-length': '0' } ] +434 verbose etag console-browserify from cache +435 silly addNameRange number 2 { name: 'console-browserify', +435 silly addNameRange range: '>=0.1.0- <0.2.0-', +435 silly addNameRange hasData: true } +436 silly addNameRange versions [ 'console-browserify', [ '0.1.0', '0.1.1', '0.1.2', '0.1.3' ] ] +437 verbose addNamed [ 'console-browserify', '0.1.3' ] +438 verbose addNamed [ '0.1.3', '0.1.3' ] +439 silly lockFile f52d299a-console-browserify-0-1-3 [email protected] +440 verbose lock [email protected] /Users/wilsonpage/.npm/f52d299a-console-browserify-0-1-3.lock +441 verbose read json /Users/wilsonpage/.npm/console-browserify/0.1.3/package/package.json +442 silly lockFile f52d299a-console-browserify-0-1-3 [email protected] +443 silly lockFile abfcf364-console-browserify-0-1-0 console-browserify@~0.1.0 +444 http 304 https://registry.npmjs.org/syntax-error +445 silly registry.get cb [ 304, +445 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +445 silly registry.get etag: '"4T9O90M0FDSNQV970DTCW6MZ9"', +445 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +445 silly registry.get 'content-length': '0' } ] +446 verbose etag syntax-error from cache +447 silly addNameRange number 2 { name: 'syntax-error', +447 silly addNameRange range: '>=0.0.0- <0.1.0-', +447 silly addNameRange hasData: true } +448 silly addNameRange versions [ 'syntax-error', [ '0.0.0' ] ] +449 verbose addNamed [ 'syntax-error', '0.0.0' ] +450 verbose addNamed [ '0.0.0', '0.0.0' ] +451 silly lockFile 8693c57b-syntax-error-0-0-0 [email protected] +452 verbose lock [email protected] /Users/wilsonpage/.npm/8693c57b-syntax-error-0-0-0.lock +453 verbose read json /Users/wilsonpage/.npm/syntax-error/0.0.0/package/package.json +454 silly lockFile 8693c57b-syntax-error-0-0-0 [email protected] +455 silly lockFile 541c7056-syntax-error-0-0-0 syntax-error@~0.0.0 +456 http 304 https://registry.npmjs.org/deputy +457 silly registry.get cb [ 304, +457 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +457 silly registry.get etag: '"4AOH7BGC316WGXVN9EL31OZ93"', +457 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +457 silly registry.get 'content-length': '0' } ] +458 verbose etag deputy from cache +459 silly addNameRange number 2 { name: 'deputy', range: '>=0.0.3- <0.1.0-', hasData: true } +460 silly addNameRange versions [ 'deputy', [ '0.0.0', '0.0.1', '0.0.2', '0.0.3', '0.0.4' ] ] +461 verbose addNamed [ 'deputy', '0.0.4' ] +462 verbose addNamed [ '0.0.4', '0.0.4' ] +463 silly lockFile 12bc9d79-deputy-0-0-4 [email protected] +464 verbose lock [email protected] /Users/wilsonpage/.npm/12bc9d79-deputy-0-0-4.lock +465 verbose read json /Users/wilsonpage/.npm/deputy/0.0.4/package/package.json +466 silly lockFile 12bc9d79-deputy-0-0-4 [email protected] +467 silly lockFile f65dca98-deputy-0-0-3 deputy@~0.0.3 +468 http 304 https://registry.npmjs.org/resolve +469 silly registry.get cb [ 304, +469 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +469 silly registry.get etag: '"1PRD1ZSWQFUUV9QIHA7G137QL"', +469 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +469 silly registry.get 'content-length': '0' } ] +470 verbose etag resolve from cache +471 http 304 https://registry.npmjs.org/nub +472 silly registry.get cb [ 304, +472 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +472 silly registry.get etag: '"13K3EU4M2PX1SLZHKRRYKF3RR"', +472 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +472 silly registry.get 'content-length': '0' } ] +473 verbose etag nub from cache +474 http 304 https://registry.npmjs.org/commondir +475 silly registry.get cb [ 304, +475 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +475 silly registry.get etag: '"CBLBPLAJ0K8OBJ8W72IANIRND"', +475 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +475 silly registry.get 'content-length': '0' } ] +476 verbose etag commondir from cache +477 silly addNameRange number 2 { name: 'nub', range: '>=0.0.0- <0.1.0-', hasData: true } +478 silly addNameRange versions [ 'nub', [ '0.0.0' ] ] +479 verbose addNamed [ 'nub', '0.0.0' ] +480 verbose addNamed [ '0.0.0', '0.0.0' ] +481 silly lockFile 34fd82fb-nub-0-0-0 [email protected] +482 verbose lock [email protected] /Users/wilsonpage/.npm/34fd82fb-nub-0-0-0.lock +483 silly addNameRange number 2 { name: 'commondir', range: '>=0.0.1- <0.1.0-', hasData: true } +484 silly addNameRange versions [ 'commondir', [ '0.0.0', '0.0.1' ] ] +485 verbose addNamed [ 'commondir', '0.0.1' ] +486 verbose addNamed [ '0.0.1', '0.0.1' ] +487 silly lockFile 56818eda-commondir-0-0-1 [email protected] +488 verbose lock [email protected] /Users/wilsonpage/.npm/56818eda-commondir-0-0-1.lock +489 verbose read json /Users/wilsonpage/.npm/nub/0.0.0/package/package.json +490 silly addNameRange number 2 { name: 'resolve', range: '>=0.2.0- <0.3.0-', hasData: true } +491 silly addNameRange versions [ 'resolve', +491 silly addNameRange [ '0.0.0', +491 silly addNameRange '0.0.1', +491 silly addNameRange '0.0.2', +491 silly addNameRange '0.0.3', +491 silly addNameRange '0.0.4', +491 silly addNameRange '0.1.0', +491 silly addNameRange '0.1.2', +491 silly addNameRange '0.1.3', +491 silly addNameRange '0.2.0', +491 silly addNameRange '0.2.1', +491 silly addNameRange '0.2.2', +491 silly addNameRange '0.2.3' ] ] +492 verbose addNamed [ 'resolve', '0.2.3' ] +493 verbose addNamed [ '0.2.3', '0.2.3' ] +494 silly lockFile 677ab067-resolve-0-2-3 [email protected] +495 verbose lock [email protected] /Users/wilsonpage/.npm/677ab067-resolve-0-2-3.lock +496 verbose read json /Users/wilsonpage/.npm/commondir/0.0.1/package/package.json +497 verbose read json /Users/wilsonpage/.npm/resolve/0.2.3/package/package.json +498 silly lockFile 34fd82fb-nub-0-0-0 [email protected] +499 silly lockFile fe411909-nub-0-0-0 nub@~0.0.0 +500 silly lockFile 56818eda-commondir-0-0-1 [email protected] +501 http 304 https://registry.npmjs.org/coffee-script +502 silly registry.get cb [ 304, +502 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +502 silly registry.get etag: '"5DVQS1LWDXJKMR2BFTU1OGKFH"', +502 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +502 silly registry.get 'content-length': '0' } ] +503 verbose etag coffee-script from cache +504 silly lockFile 677ab067-resolve-0-2-3 [email protected] +505 silly lockFile d18c18a5-commondir-0-0-1 commondir@~0.0.1 +506 silly lockFile eb1ed680-resolve-0-2-0 resolve@~0.2.0 +507 silly addNameRange number 2 { name: 'coffee-script', +507 silly addNameRange range: '>=1.0.0- <2.0.0-', +507 silly addNameRange hasData: true } +508 silly addNameRange versions [ 'coffee-script', +508 silly addNameRange [ '0.7.0', +508 silly addNameRange '0.7.1', +508 silly addNameRange '0.7.2', +508 silly addNameRange '0.9.0', +508 silly addNameRange '0.9.1', +508 silly addNameRange '0.9.2', +508 silly addNameRange '0.9.3', +508 silly addNameRange '0.9.4', +508 silly addNameRange '0.9.5', +508 silly addNameRange '0.9.6', +508 silly addNameRange '1.0.0', +508 silly addNameRange '1.0.1', +508 silly addNameRange '1.1.0', +508 silly addNameRange '1.1.1', +508 silly addNameRange '1.1.2', +508 silly addNameRange '1.1.3', +508 silly addNameRange '1.2.0', +508 silly addNameRange '1.3.0', +508 silly addNameRange '1.3.1', +508 silly addNameRange '1.3.2', +508 silly addNameRange '1.3.3', +508 silly addNameRange '1.4.0' ] ] +509 verbose addNamed [ 'coffee-script', '1.4.0' ] +510 verbose addNamed [ '1.4.0', '1.4.0' ] +511 silly lockFile 0c6dfe35-coffee-script-1-4-0 [email protected] +512 verbose lock [email protected] /Users/wilsonpage/.npm/0c6dfe35-coffee-script-1-4-0.lock +513 verbose read json /Users/wilsonpage/.npm/coffee-script/1.4.0/package/package.json +514 silly lockFile 0c6dfe35-coffee-script-1-4-0 [email protected] +515 silly lockFile edf96972-coffee-script-1-x-x [email protected] +516 http 304 https://registry.npmjs.org/optimist +517 silly registry.get cb [ 304, +517 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +517 silly registry.get etag: '"EH1DT6319Y8YFU4ST3I7HOF8V"', +517 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +517 silly registry.get 'content-length': '0' } ] +518 verbose etag optimist from cache +519 silly addNameRange number 2 { name: 'optimist', range: '>=0.3.4- <0.4.0-', hasData: true } +520 silly addNameRange versions [ 'optimist', +520 silly addNameRange [ '0.0.1', +520 silly addNameRange '0.0.2', +520 silly addNameRange '0.0.4', +520 silly addNameRange '0.0.5', +520 silly addNameRange '0.0.6', +520 silly addNameRange '0.0.7', +520 silly addNameRange '0.1.0', +520 silly addNameRange '0.1.1', +520 silly addNameRange '0.1.2', +520 silly addNameRange '0.1.3', +520 silly addNameRange '0.1.4', +520 silly addNameRange '0.1.5', +520 silly addNameRange '0.1.6', +520 silly addNameRange '0.1.7', +520 silly addNameRange '0.1.8', +520 silly addNameRange '0.1.9', +520 silly addNameRange '0.0.3', +520 silly addNameRange '0.2.0', +520 silly addNameRange '0.2.1', +520 silly addNameRange '0.2.2', +520 silly addNameRange '0.2.3', +520 silly addNameRange '0.2.4', +520 silly addNameRange '0.2.5', +520 silly addNameRange '0.2.6', +520 silly addNameRange '0.2.7', +520 silly addNameRange '0.2.8', +520 silly addNameRange '0.3.0', +520 silly addNameRange '0.3.1', +520 silly addNameRange '0.3.3', +520 silly addNameRange '0.3.4', +520 silly addNameRange '0.3.5' ] ] +521 verbose addNamed [ 'optimist', '0.3.5' ] +522 verbose addNamed [ '0.3.5', '0.3.5' ] +523 silly lockFile 72e2da2d-optimist-0-3-5 [email protected] +524 verbose lock [email protected] /Users/wilsonpage/.npm/72e2da2d-optimist-0-3-5.lock +525 verbose read json /Users/wilsonpage/.npm/optimist/0.3.5/package/package.json +526 silly lockFile 72e2da2d-optimist-0-3-5 [email protected] +527 silly lockFile 094c60bd-optimist-0-3-4 optimist@~0.3.4 +528 http 304 https://registry.npmjs.org/http-browserify +529 silly registry.get cb [ 304, +529 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +529 silly registry.get etag: '"3ZSAXT2SH4DEHT45GPONPV899"', +529 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +529 silly registry.get 'content-length': '0' } ] +530 verbose etag http-browserify from cache +531 silly addNameRange number 2 { name: 'http-browserify', +531 silly addNameRange range: '>=0.1.1- <0.2.0-', +531 silly addNameRange hasData: true } +532 silly addNameRange versions [ 'http-browserify', +532 silly addNameRange [ '0.0.0', +532 silly addNameRange '0.0.1', +532 silly addNameRange '0.0.2', +532 silly addNameRange '0.0.3', +532 silly addNameRange '0.1.0', +532 silly addNameRange '0.1.1', +532 silly addNameRange '0.1.2', +532 silly addNameRange '0.1.3', +532 silly addNameRange '0.1.4', +532 silly addNameRange '0.1.5', +532 silly addNameRange '0.1.6' ] ] +533 verbose addNamed [ 'http-browserify', '0.1.6' ] +534 verbose addNamed [ '0.1.6', '0.1.6' ] +535 silly lockFile a3526272-http-browserify-0-1-6 [email protected] +536 verbose lock [email protected] /Users/wilsonpage/.npm/a3526272-http-browserify-0-1-6.lock +537 verbose read json /Users/wilsonpage/.npm/http-browserify/0.1.6/package/package.json +538 silly lockFile a3526272-http-browserify-0-1-6 [email protected] +539 http 304 https://registry.npmjs.org/crypto-browserify +540 silly registry.get cb [ 304, +540 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +540 silly registry.get etag: '"1MSPD2DY9YO38O07CEG61QQT0"', +540 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +540 silly registry.get 'content-length': '0' } ] +541 verbose etag crypto-browserify from cache +542 silly lockFile 83e61da6-http-browserify-0-1-1 http-browserify@~0.1.1 +543 silly addNameRange number 2 { name: 'crypto-browserify', +543 silly addNameRange range: '>=0.0.0- <1.0.0-', +543 silly addNameRange hasData: true } +544 silly addNameRange versions [ 'crypto-browserify', +544 silly addNameRange [ '0.0.0', '0.0.1', '0.1.0', '0.1.1', '0.1.2', '0.2.0', '0.2.1' ] ] +545 verbose addNamed [ 'crypto-browserify', '0.2.1' ] +546 verbose addNamed [ '0.2.1', '0.2.1' ] +547 silly lockFile fd6b21c3-crypto-browserify-0-2-1 [email protected] +548 verbose lock [email protected] /Users/wilsonpage/.npm/fd6b21c3-crypto-browserify-0-2-1.lock +549 verbose read json /Users/wilsonpage/.npm/crypto-browserify/0.2.1/package/package.json +550 http 304 https://registry.npmjs.org/vm-browserify +551 silly registry.get cb [ 304, +551 silly registry.get { server: 'CouchDB/1.2.1 (Erlang OTP/R15B)', +551 silly registry.get etag: '"2XG3HQ3T4VY572CS9AFY94WQU"', +551 silly registry.get date: 'Tue, 29 Jan 2013 16:11:46 GMT', +551 silly registry.get 'content-length': '0' } ] +552 verbose etag vm-browserify from cache +553 silly lockFile fd6b21c3-crypto-browserify-0-2-1 [email protected] +554 silly lockFile e9cc4b31-crypto-browserify-0 crypto-browserify@~0 +555 silly addNameRange number 2 { name: 'vm-browserify', +555 silly addNameRange range: '>=0.0.0- <0.1.0-', +555 silly addNameRange hasData: true } +556 silly addNameRange versions [ 'vm-browserify', [ '0.0.0', '0.0.1' ] ] +557 verbose addNamed [ 'vm-browserify', '0.0.1' ] +558 verbose addNamed [ '0.0.1', '0.0.1' ] +559 silly lockFile 1b64966c-vm-browserify-0-0-1 [email protected] +560 verbose lock [email protected] /Users/wilsonpage/.npm/1b64966c-vm-browserify-0-0-1.lock +561 verbose read json /Users/wilsonpage/.npm/vm-browserify/0.0.1/package/package.json +562 silly lockFile 1b64966c-vm-browserify-0-0-1 [email protected] +563 silly lockFile 29145f01-vm-browserify-0-0-0 vm-browserify@~0.0.0 +564 silly resolved [ { name: 'detective', +564 silly resolved description: 'Find all calls to require() no matter how crazily nested using a proper walk of the AST', +564 silly resolved version: '0.2.1', +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/substack/node-detective.git' }, +564 silly resolved main: 'index.js', +564 silly resolved keywords: [ 'require', 'source', 'analyze', 'ast' ], +564 silly resolved directories: { lib: '.', example: 'example', test: 'test' }, +564 silly resolved scripts: { test: 'tap test/*.js' }, +564 silly resolved dependencies: { esprima: '~0.9.9' }, +564 silly resolved devDependencies: { tap: '~0.2.6' }, +564 silly resolved engines: { node: '>=0.6.0' }, +564 silly resolved license: 'MIT', +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved readme: 'detective\n=========\n\nFind all calls to require() no matter how crazily nested using a proper walk of\nthe AST.\n\n[](http://travis-ci.org/substack/node-detective)\n\nexample\n=======\n\nstrings\n-------\n\nstrings_src.js:\n\n````javascript\nvar a = require(\'a\');\nvar b = require(\'b\');\nvar c = require(\'c\');\n````\n\nstrings.js:\n\n````javascript\nvar detective = require(\'detective\');\nvar fs = require(\'fs\');\n\nvar src = fs.readFileSync(__dirname + \'/strings_src.js\');\nvar requires = detective(src);\nconsole.dir(requires);\n````\n\noutput:\n\n $ node examples/strings.js\n [ \'a\', \'b\', \'c\' ]\n\nmethods\n=======\n\nvar detective = require(\'detective\');\n\ndetective(src, opts)\n--------------------\n\nGive some source body `src`, return an array of all the require()s with string\narguments.\n\nThe options parameter `opts` is passed along to `detective.find()`.\n\ndetective.find(src, opts)\n-------------------------\n\nGive some source body `src`, return an object with "strings" and "expressions"\narrays for each of the require() calls.\n\nThe "expressions" array will contain the stringified expressions.\n\nOptionally you can specify a different function besides `"require"` to analyze\nwith `opts.word`.\n\ninstallation\n============\n\n npm install detective\n', +564 silly resolved readmeFilename: 'README.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'detective@~0.2.0' }, +564 silly resolved { name: 'buffer-browserify', +564 silly resolved version: '0.0.4', +564 silly resolved description: 'buffer module compatibility for browserify', +564 silly resolved main: 'index.js', +564 silly resolved browserify: 'index.js', +564 silly resolved directories: { test: 'test' }, +564 silly resolved dependencies: { 'base64-js': '0.0.2' }, +564 silly resolved devDependencies: { tap: '0.2.x' }, +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'http://github.com/toots/buffer-browserify.git' }, +564 silly resolved keywords: [ 'buffer', 'browserify', 'compatible', 'meatless', 'browser' ], +564 silly resolved author: { name: 'Romain Beauxis', email: '[email protected]' }, +564 silly resolved scripts: { test: 'node node_modules/tap/bin/tap.js test/*.js' }, +564 silly resolved license: 'MIT/X11', +564 silly resolved engine: { node: '>=0.6' }, +564 silly resolved readme: 'buffer-browserify\n===============\n\nThe buffer module from [node.js](http://nodejs.org/),\nbut for browsers.\n\nWhen you `require(\'buffer\')` in\n[browserify](http://github.com/substack/node-browserify),\nthis module will be loaded.\n\nIt will also be loaded if you use the global `Buffer` variable.\n', +564 silly resolved readmeFilename: 'README.md', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'buffer-browserify@~0.0.1' }, +564 silly resolved { name: 'console-browserify', +564 silly resolved version: '0.1.3', +564 silly resolved description: 'Emulate console for all the browsers', +564 silly resolved keywords: [], +564 silly resolved author: { name: 'Raynos', email: '[email protected]' }, +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/Raynos/console-browserify.git' }, +564 silly resolved main: 'index', +564 silly resolved homepage: 'https://github.com/Raynos/console-browserify', +564 silly resolved contributors: [ [Object] ], +564 silly resolved bugs: +564 silly resolved { url: 'https://github.com/Raynos/console-browserify/issues', +564 silly resolved email: '[email protected]' }, +564 silly resolved dependencies: { 'date-now': '~0.1.1' }, +564 silly resolved devDependencies: +564 silly resolved { tape: '~0.2.2', +564 silly resolved browserify: 'https://github.com/raynos/node-browserify/tarball/master', +564 silly resolved testem: '~0.2.55' }, +564 silly resolved licenses: [ [Object] ], +564 silly resolved scripts: +564 silly resolved { test: 'node ./test', +564 silly resolved build: 'browserify test/index.js -o test/static/bundle.js', +564 silly resolved testem: 'testem', +564 silly resolved postinstall: 'npm dedup' }, +564 silly resolved testling: { files: 'test/index.js', browsers: [Object] }, +564 silly resolved readme: '# console-browserify\n\n[![build status][1]][2]\n\n[![browser support][3]][4]\n\nEmulate console for all the browsers\n\n## Example\n\n```js\nvar console = require("console-browserify")\n\nconsole.log("hello world!")\n```\n\n## Installation\n\n`npm install console-browserify`\n\n## Contributors\n\n - Raynos\n\n## MIT Licenced\n\n\n\n [1]: https://secure.travis-ci.org/Raynos/console-browserify.png\n [2]: http://travis-ci.org/Raynos/console-browserify\n [3]: http://ci.testling.com/Raynos/console-browserify.png\n [4]: http://ci.testling.com/Raynos/console-browserify\n', +564 silly resolved readmeFilename: 'README.md', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'console-browserify@~0.1.0' }, +564 silly resolved { name: 'syntax-error', +564 silly resolved version: '0.0.0', +564 silly resolved description: 'detect and report syntax errors in source code strings', +564 silly resolved main: 'index.js', +564 silly resolved bin: {}, +564 silly resolved directories: { example: 'example', test: 'test' }, +564 silly resolved dependencies: { esprima: '~0.9.9' }, +564 silly resolved devDependencies: { tap: '~0.3.0' }, +564 silly resolved scripts: { test: 'tap test/*.js' }, +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/substack/node-syntax-error.git' }, +564 silly resolved homepage: 'https://github.com/substack/node-syntax-error', +564 silly resolved keywords: [ 'syntax', 'error', 'esprima', 'stack', 'line', 'column' ], +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved license: 'MIT', +564 silly resolved engine: { node: '>=0.6' }, +564 silly resolved readme: '# syntax-error\n\nDetect and report syntax errors in source code strings.\n\n[](http://travis-ci.org/substack/node-syntax-error)\n\nWhen you type `node src.js` you get a friendly error report about exactly where\nthe syntax error is. This module lets you check for syntax errors and report\nthem in a similarly friendly format that wrapping a try/catch around\n`Function()` or `vm.runInNewContext()` doesn\'t get you.\n\n# example\n\n``` js\nvar fs = require(\'fs\');\nvar check = require(\'syntax-error\');\n\nvar file = __dirname + \'/src.js\';\nvar src = fs.readFileSync(file);\n\nvar err = check(src, file);\nif (err) {\n console.error(\'ERROR DETECTED\' + Array(62).join(\'!\'));\n console.error(err);\n console.error(Array(76).join(\'-\'));\n}\n```\n\n***\n\n```\n$ node check.js\nERROR DETECTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n/home/substack/projects/node-syntax-error/example/src.js:5\n if (Array.isArray(x) res.push.apply(res, x);\n ^\nParseError: Unexpected identifier\n---------------------------------------------------------------------------\n```\n\n# methods\n\n``` js\nvar check = require(\'syntax-error\')\n```\n\n## var err = check(src, file)\n\nCheck the source code string `src` for syntax errors.\nOptionally you can specify a filename `file` that will show up in the output.\n\nIf `src` has a syntax error, return an error object `err` that can be printed or\nstringified.\n\nIf there are no syntax errors in `src`, return `undefined`.\n\n## err.toString()\n\nReturn the long string description with a source snippet and a `^` under\npointing exactly where the error was detected.\n\n# attributes\n\n## err.message\n\nshort string description of the error type\n\n## err.line\n\nline number of the error in the original source (indexing starts at 1)\n\n## err.column\n\ncolumn number of the error in the original source (indexing starts at 1)\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install syntax-error\n```\n\n# license\n\nMIT\n', +564 silly resolved readmeFilename: 'readme.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'syntax-error@~0.0.0' }, +564 silly resolved { name: 'deputy', +564 silly resolved description: 'caching layer for detective', +564 silly resolved version: '0.0.4', +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/substack/node-deputy.git' }, +564 silly resolved main: 'index.js', +564 silly resolved keywords: [ 'detective', 'require', 'cache' ], +564 silly resolved directories: { lib: '.', example: 'example', test: 'test' }, +564 silly resolved scripts: { test: 'tap test/*.js' }, +564 silly resolved dependencies: { mkdirp: '~0.3.3', detective: '~0.2.0' }, +564 silly resolved devDependencies: { tap: '0.0.x' }, +564 silly resolved engines: { node: '>=0.4.0' }, +564 silly resolved license: 'MIT', +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved readme: 'deputy\n======\n\nThis module is a caching layer around\n[node-detective](http://github.com/substack/node-detective).\n\n[](http://travis-ci.org/substack/node-deputy)\n\nexample\n=======\n\ncache.js\n--------\n\n``` js\nvar deputy = require(\'deputy\');\nvar detective = deputy(process.env.HOME + \'/.config/deputy.json\');\n\nvar deps = detective.find(\'require("a"); require("b")\');\nconsole.dir(deps);\n```\n\noutput:\n\n```\n$ node cache.js \n{ strings: [ \'a\', \'b\' ], expressions: [] }\n$ cat ~/.config/deputy.json \n{"55952d490bd28e3e256f0b036ced834d":{"strings":["a","b"],"expressions":[]}}\n```\n\nmethods\n=======\n\n``` js\nvar deputy = require(\'deputy\')\n```\n\nvar detective = deputy(cacheFile)\n---------------------------------\n\nReturn a new [detective](http://github.com/substack/node-detective)\nobject using `cacheFile` for caching.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n npm install deputy\n\nlicense\n=======\n\nMIT/X11\n', +564 silly resolved readmeFilename: 'README.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'deputy@~0.0.3' }, +564 silly resolved { name: 'nub', +564 silly resolved version: '0.0.0', +564 silly resolved description: 'Uniqueness functions', +564 silly resolved main: 'index.js', +564 silly resolved directories: { lib: '.', example: 'example', test: 'test' }, +564 silly resolved dependencies: {}, +564 silly resolved devDependencies: { expresso: '0.7.x' }, +564 silly resolved scripts: { test: 'expresso' }, +564 silly resolved repository: { type: 'git', url: 'http://github.com/substack/node-nub.git' }, +564 silly resolved keywords: [ 'unique', 'uniq', 'uniqBy', 'nub', 'nubBy' ], +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved license: 'MIT/X11', +564 silly resolved engine: { node: '>=0.4' }, +564 silly resolved readme: 'nub\n===\n\nReturn all the unique elements of an array. You can specify your own uniqueness\ncomparison function with `nub.by` too.\n\nThese work like haskell\'s `nub` and `nubBy` functions in Data.List.\n\nmethods\n=======\n\nnub(xs)\n-------\n\nReturn a new array with all the uniqe elements in `xs`.\n\nUniqueness is calculated `===` style so the types matter.\n\nnub.by(xs, cmp)\n---------------\n\nUse `cmp(x,y)` function to compare elements instead of the default.\n`cmp` should return whether the two elements are equal as a boolean.\n', +564 silly resolved readmeFilename: 'README.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'nub@~0.0.0' }, +564 silly resolved { name: 'commondir', +564 silly resolved version: '0.0.1', +564 silly resolved description: 'Compute the closest common parent for file paths', +564 silly resolved main: 'index.js', +564 silly resolved directories: { lib: '.', example: 'example', test: 'test' }, +564 silly resolved dependencies: {}, +564 silly resolved devDependencies: { expresso: '0.7.x' }, +564 silly resolved scripts: { test: 'expresso' }, +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'http://github.com/substack/node-commondir.git' }, +564 silly resolved keywords: [ 'common', 'path', 'directory', 'file', 'parent', 'root' ], +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved license: 'MIT/X11', +564 silly resolved engine: { node: '>=0.4' }, +564 silly resolved readme: 'commondir\n=========\n\nCompute the closest common parent directory among an array of directories.\n\nexample\n=======\n\ndir\n---\n\n > var commondir = require(\'commondir\');\n > commondir([ \'/x/y/z\', \'/x/y\', \'/x/y/w/q\' ])\n \'/x/y\'\n\nbase\n----\n\n > var commondir = require(\'commondir\')\n > commondir(\'/foo/bar\', [ \'../baz\', \'../../foo/quux\', \'./bizzy\' ])\n \'/foo\'\n\nmethods\n=======\n\nvar commondir = require(\'commondir\');\n\ncommondir(absolutePaths)\n------------------------\n\nCompute the closest common parent directory for an array `absolutePaths`.\n\ncommondir(basedir, relativePaths)\n---------------------------------\n\nCompute the closest common parent directory for an array `relativePaths` which\nwill be resolved for each `dir` in `relativePaths` according to:\n`path.resolve(basedir, dir)`.\n\ninstallation\n============\n\nUsing [npm](http://npmjs.org), just do:\n\n npm install commondir\n', +564 silly resolved readmeFilename: 'README.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'commondir@~0.0.1' }, +564 silly resolved { name: 'resolve', +564 silly resolved description: 'A more hookable require.resolve() implementation', +564 silly resolved version: '0.2.3', +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/substack/node-resolve.git' }, +564 silly resolved main: 'index.js', +564 silly resolved keywords: [ 'resolve', 'require', 'node', 'module' ], +564 silly resolved directories: { lib: '.', example: 'example', test: 'test' }, +564 silly resolved scripts: { test: 'tap test/*.js' }, +564 silly resolved dependencies: {}, +564 silly resolved devDependencies: { tap: '~0.2.4' }, +564 silly resolved engines: { node: '>=0.4.0' }, +564 silly resolved license: 'MIT', +564 silly resolved author: +564 silly resolved { name: 'James Halliday', +564 silly resolved email: '[email protected]', +564 silly resolved url: 'http://substack.net' }, +564 silly resolved readme: 'resolve\n=======\n\nImplements the [node `require.resolve()`\nalgorithm](http://nodejs.org/docs/v0.4.8/api/all.html#all_Together...)\nexcept you can pass in the file to compute paths relatively to along with your\nown `require.paths` without updating the global copy (which doesn\'t even work in\nnode `>=0.5`).\n\n[](http://travis-ci.org/substack/node-resolve)\n\nmethods\n=======\n\nvar resolve = require(\'resolve\');\n\nresolve.sync(pkg, opts)\n-----------------------\n\nSynchronously search for the package/filename string `pkg`\naccording to the [`require.resolve()`\nalgorithm](http://nodejs.org/docs/v0.4.8/api/all.html#all_Together...)\nfor `X=pkg` and `Y=opts.basedir`.\n\nDefault values for `opts`:\n\n````javascript\n{\n paths : [],\n basedir : __dirname,\n extensions : [ \'.js\' ],\n readFileSync : fs.readFileSync,\n isFile : function (file) {\n return path.existSync(file) && fs.statSync(file).isFile()\n }\n}\n````\n\nOptionally you can specify a `opts.packageFilter` function to map the contents\nof `JSON.parse()`\'d package.json files.\n\nIf nothing is found, all of the directories in `opts.paths` are searched.\n\nresolve.isCore(pkg)\n-------------------\n\nReturn whether a package is in core.\n', +564 silly resolved readmeFilename: 'README.markdown', +564 silly resolved _id: '[email protected]', +564 silly resolved _from: 'resolve@~0.2.0' }, +564 silly resolved { name: 'coffee-script', +564 silly resolved description: 'Unfancy JavaScript', +564 silly resolved keywords: [ 'javascript', 'language', 'coffeescript', 'compiler' ], +564 silly resolved author: { name: 'Jeremy Ashkenas' }, +564 silly resolved version: '1.4.0', +564 silly resolved licenses: [ [Object] ], +564 silly resolved engines: { node: '>=0.4.0' }, +564 silly resolved directories: { lib: './lib/coffee-script' }, +564 silly resolved main: './lib/coffee-script/coffee-script', +564 silly resolved bin: { coffee: './bin/coffee', cake: './bin/cake' }, +564 silly resolved scripts: { test: 'node ./bin/cake test' }, +564 silly resolved homepage: 'http://coffeescript.org', +564 silly resolved bugs: 'https://github.com/jashkenas/coffee-script/issues', +564 silly resolved repository: +564 silly resolved { type: 'git', +564 silly resolved url: 'git://github.com/jashkenas/coffee-script.git' }, +564 silly resolved devDependencies: { 'uglify-js': '>=1.0.0', jison: '>=0.2.0' }, +564 silly resolved readme: '\n {\n } } {\n { { } }\n } }{ {\n { }{ } } _____ __ __\n ( }{ }{ { ) / ____| / _|/ _|\n .- { { } { }} -. | | ___ | |_| |_ ___ ___\n ( ( } { } { } } ) | | / _ \\| _| _/ _ \\/ _ \\\n |`-..________ ..-\'| | |___| (_) | | | || __/ __/\n | | \\_____\\___/|_| |_| \\___|\\___|\n | ;--.\n | (__ \\ _____ _ _\n | | ) ) / ____| (_) | |\n | |/ / | (___ ___ _ __ _ _ __ | |_\n | ( / \\___ \\ / __| \'__| | \'_ \\| __|\n | |/ ____) | (__| | | | |_) | |_\n | | |_____/ \\___|_| |_| .__/ \\__|\n `-.._________..-\' | |\n |_|\n\n\n CoffeeScript is a little language that compiles into JavaScript.\n\n Install Node.js, and then the CoffeeScript compiler:\n sudo bin/cake install\n\n Or, if you have the Node Package Manager installed:\n npm install -g coffee-script\n (Leave off the | 2,410 | Merge branch '0.2' | 0 | .log | log | mit | ftlabs/fruitmachine |
10067193 | <NME> .gitignore
<BEF> .DS_Store
node_modules
npm-debug.log
artwork
coverage
<MSG> - Removed .DS_Store
<DFF> @@ -0,0 +1,2 @@
+/old
+.DS_Store
\ No newline at end of file
| 2 | - Removed .DS_Store | 0 | gitignore | mit | ftlabs/fruitmachine |
|
10067194 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067195 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067196 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067197 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067198 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067199 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067200 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067201 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067202 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067203 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067204 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067205 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067206 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067207 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067208 | <NME> VisualLine.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
}
}
internal sealed class VisualLineDrawingVisual : Layoutable
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> Completion window (#12)
Completion window
<DFF> @@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
-using Avalonia.Layout;
+using Avalonia.Controls;
using Avalonia.Media;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
@@ -749,7 +749,8 @@ namespace AvaloniaEdit.Rendering
}
}
- internal sealed class VisualLineDrawingVisual : Layoutable
+ // TODO: can inherit from Layoutable, but dev tools crash
+ internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
| 3 | Completion window (#12) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067209 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067210 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067211 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067212 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067213 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067214 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067215 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067216 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067217 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067218 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067219 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067220 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067221 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067222 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067223 | <NME> AvaloniaEdit.sln
<BEF>
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E9668961-BD19-4360-8ABE-B9BD55EB52CA}"
ProjectSection(SolutionItems) = preProject
azure-pipelines.yml = azure-pipelines.yml
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.ActiveCfg = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Debug|x64.Build.0 = Debug|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|Any CPU.Build.0 = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.ActiveCfg = Release|Any CPU
{4B04026F-BA96-4721-AE28-0970CB5806A9}.Release|x64.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.ActiveCfg = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Debug|x64.Build.0 = Debug|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|Any CPU.Build.0 = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.ActiveCfg = Release|Any CPU
{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}.Release|x64.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.ActiveCfg = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Debug|x64.Build.0 = Debug|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|Any CPU.Build.0 = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.ActiveCfg = Release|Any CPU
{9E5D4372-D362-44A2-984D-578288870AB8}.Release|x64.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.ActiveCfg = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Debug|x64.Build.0 = Debug|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|Any CPU.Build.0 = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.ActiveCfg = Release|Any CPU
{63826C17-C08C-4E5F-AABB-443EBA565E92}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DCA3703C-8F8E-4AC5-81D7-65131FEBA631}
EndGlobalSection
EndGlobal
<MSG> Moved solution file
<DFF> @@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
| 2 | Moved solution file | 2 | .sln | sln | mit | AvaloniaUI/AvaloniaEdit |
10067224 | <NME> README.md
<BEF> # Lumen Passport
[](https://travis-ci.org/dusterio/lumen-passport)
[](https://codeclimate.com/github/dusterio/lumen-passport/badges)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
> Making Laravel Passport work with Lumen
## Introduction
It's a simple service provider that makes **Laravel Passport** work with **Lumen**.
## Installation
First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet.
Then install **Lumen Passport**:
```bash
composer require dusterio/lumen-passport
```
Or if you prefer, edit `composer.json` manually and run then `composer update`:
```json
{
"require": {
"dusterio/lumen-passport": "^0.3.5"
}
}
```
### Modify the bootstrap flow
We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider:
```php
/** @file bootstrap/app.php */
// Enable Facades
$app->withFacades();
// Enable Eloquent
$app->withEloquent();
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
// Register two service providers, Laravel Passport and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
```
### Laravel Passport ^7.3.2 and newer
On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows:
```php
/** @file bootstrap/app.php */
//$app = new Laravel\Lumen\Application(
// dirname(__DIR__)
//);
$app = new \Dusterio\LumenPassport\Lumen7Application(
dirname(__DIR__)
);
```
\* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._
### Migrate and install Laravel Passport
```bash
# Create new tables for Passport
php artisan migrate
# Install encryption keys and other stuff for Passport
php artisan passport:install
```
It will output the Personal access client ID and secret, and the Password grand client ID and secret.
\* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._
## Configuration
### Configure Authentication
Edit `config/auth.php` to suit your needs. A simple example:
```php
/** @file config/auth.php */
return [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
],
];
```
\* _Note: Lumen 7.x and older uses `\App\User::class`_
Load the config since Lumen doesn't load config files automatically:
```php
/** @file bootstrap/app.php */
$app->configure('auth');
];
```
## User model
Make sure your user model uses Passport's ```HasApiTokens``` trait, eg.:
```
### User model
Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait.
```php
/** @file app/Models/User.php */
use Laravel\Passport\HasApiTokens;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use HasApiTokens, Authenticatable, Authorizable, HasFactory;
/* rest of the model */
}
```
## Usage
You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport).
### Curl example with username and password authentication
First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests.
```bash
# Request
curl --location --request POST '{{APP_URL}}/oauth/token' \
--header 'Content-Type: application/json' \
--data-raw '{
"grant_type": "password",
"client_id": "{{CLIENT_ID}}",
"client_secret": "{{CLIENT_SECRET}}",
"username": "{{USER_EMAIL}}",
"password": "{{USER_PASSWORD}}",
"scope": "*"
}'
```
```json
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "******",
"refresh_token": "******"
}
```
And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**.
```php
/** @file routes/web.php */
$router->get('/ping', ['middleware' => 'auth', fn () => 'pong']);
```
```bash
# Request
curl --location --request GET '{{APP_URL}}/ping' \
--header 'Authorization: Bearer {{ACCESS_TOKEN}}'
```
```html
pong
```
### Installed routes
This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`:
Verb | Path | Controller | Action | Middleware
--- | --- | --- | --- | ---
POST | /oauth/token | AccessTokenController | issueToken | -
GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth
DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth
POST | /oauth/token/refresh | TransientTokenController | refresh | auth
GET | /oauth/clients | ClientController | forUser | auth
POST | /oauth/clients | ClientController | store | auth
PUT | /oauth/clients/{client_id} | ClientController | update | auth
DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth
GET | /oauth/scopes | ScopeController | all | auth
GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth
POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth
DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth
\* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._
## Extra features
There are a couple of extra features that aren't present in **Laravel Passport**
### Prefixing Routes
You can add that into an existing group, or add use this route registrar independently like so;
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
/* rest of boot */
}
}
```
### Multiple tokens per client
Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers
simultaneously. Currently **Laravel Passport** does not allow that.
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
LumenPassport::allowMultipleTokens();
/* rest of boot */
}
}
```
### Different TTLs for different password clients
**Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users).
Simply do the following in your service provider:
```php
/** @file app/Providers/AuthServiceProvider.php */
use Carbon\Carbon;
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
$client_id = '1';
LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id);
/* rest of boot */
}
}
```
If you don't specify client Id, it will simply fall back to Laravel Passport implementation.
### Purge expired tokens
```bash
php artisan passport:purge
```
Simply run it to remove expired refresh tokens and their corresponding access tokens from the database.
## Error and issue resolution
Instead of opening a new issue, please see if someone has already had it and it has been resolved.
If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md).
## Video tutorials
I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps.
Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :)
## License
The MIT License (MIT)
Copyright (c) 2016 Denis Mysenko
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.
<MSG> Updated documentation with hints from that of laravel/passport
<DFF> @@ -119,6 +119,20 @@ return [
];
```
+## Registering Routes
+
+Next, you should call the LumenPassport::routes method within the boot method of your application. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
+
+```php
+Dusterio\LumenPassport\LumenPassport::routes($app);
+```
+
+You can add that into an existing group, or add use this route registrar independently like so;
+
+```php
+Dusterio\LumenPassport\LumenPassport::routes($app, ['prefix' => 'v1/oauth']);
+```
+
## User model
Make sure your user model uses Passport's ```HasApiTokens``` trait, eg.:
| 14 | Updated documentation with hints from that of laravel/passport | 0 | .md | md | mit | dusterio/lumen-passport |
10067225 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067226 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067227 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067228 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067229 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067230 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067231 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067232 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067233 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067234 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067235 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067236 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067237 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067238 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067239 | <NME> pascal.tmLanguage.json
<BEF> ADDFILE
<MSG> Merge pull request #198 from AlphaNecron/dev
textmate: added pascal highlighting
<DFF> @@ -0,0 +1,779 @@
+{
+ "information_for_contributors": [
+ "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml",
+ "If you want to provide a fix or improvement, please create a pull request against the original repository.",
+ "Once accepted there, we are happy to receive an update request."
+ ],
+ "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b",
+ "name": "Pascal",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#program"
+ },
+ {
+ "include": "#unit"
+ },
+ {
+ "include": "#interface"
+ },
+ {
+ "include": "#implementation"
+ },
+ {
+ "include": "#unit-main"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "meta.program.end.pascal",
+ "match": "(?i)\\b(end)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ }
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ },
+ {
+ "include": "#keywords"
+ }
+ ],
+ "repository": {
+ "comment": {
+ "patterns": [
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\(\\*",
+ "end": "\\*\\)"
+ },
+ {
+ "name": "comment.block.pascal",
+ "begin": "\\{",
+ "end": "\\}"
+ },
+ {
+ "name": "comment.line.pascal",
+ "match": "//.*$"
+ }
+ ]
+ },
+ "program": {
+ "name": "meta.program.pascal",
+ "begin": "(?i)\\b(program)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ }
+ ]
+ },
+ "unit": {
+ "name": "meta.unit.pascal",
+ "begin": "(?i)\\b(unit)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "interface": {
+ "name": "meta.interface.pascal",
+ "begin": "(?i)\\b(interface)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(implementation)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "implementation": {
+ "name": "meta.implementation.pascal",
+ "begin": "(?i)\\b(implementation)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\b(initialization|end)\\b)",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#uses"
+ },
+ {
+ "include": "#label"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#function-body"
+ },
+ {
+ "include": "#function-mod"
+ },
+ {
+ "include": "#type-declaration"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "unit-main": {
+ "begin": "(?i)\\b(initialization)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*\\.",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(finalization)\\b"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "uses": {
+ "name": "meta.uses.pascal",
+ "begin": "(?i)\\b(uses)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.declaration.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "label": {
+ "name": "meta.label.pascal",
+ "begin": "(?i)\\b(label)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "string.unquoted.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ }
+ ]
+ },
+ "function-declaration": {
+ "name": "meta.function.pascal",
+ "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "storage.type.pascal"
+ }
+ },
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.",
+ "captures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ }
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": "(?i)([_a-z][0-9_a-z]*)"
+ },
+ {
+ "include": "#parameter-list"
+ },
+ {
+ "begin": ":",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ },
+ "function-body": {
+ "name": "meta.body.pascal",
+ "begin": "(?i)\\b(begin)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\s*[;|\\.]",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "function-mod": {
+ "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(name)\\b"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "asm": {
+ "contentName": "meta.embedded.asm",
+ "begin": "(?i)(asm)",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b([^;]*);",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#strings"
+ }
+ ]
+ }
+ },
+ "patterns": []
+ },
+ "type-declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\btype\\b"
+ },
+ {
+ "name": "meta.type.alias.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)",
+ "beginCaptures": {
+ "1": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "begin": "=",
+ "end": "(?=;)",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "declaration": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(const|type|var)\\b"
+ },
+ {
+ "name": "meta.declaration.pascal",
+ "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "variable.other.pascal"
+ }
+ },
+ "end": "(;|,|(?=\\)))",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": ":",
+ "end": "(?=[;=)])",
+ "patterns": [
+ {
+ "include": "#type"
+ }
+ ]
+ },
+ {
+ "name": "meta.expression.pascal",
+ "match": "=([^;\\)]*)",
+ "captures": {
+ "1": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ "parameter-list": {
+ "name": "meta.parameterlist.pascal",
+ "begin": "\\(",
+ "end": "\\)",
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "type": {
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#class-declaration"
+ },
+ {
+ "include": "#record-declaration"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "begin": "\\[",
+ "end": "\\]",
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b[_a-z][0-9_a-z]*\\b"
+ }
+ ]
+ },
+ "record-declaration": {
+ "begin": "(?i)\\b(record)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "begin": "(?i)\\b(case)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i)\\b(of)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)(?=\\bend\\b)",
+ "patterns": [
+ {
+ "begin": "(?i):\\s*\\(",
+ "end": "(?i)\\)\\s*",
+ "patterns": [
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "class-declaration": {
+ "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ },
+ "2": {
+ "name": "entity.name.type.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "name": "storage.type.method.pascal",
+ "match": "(?i)(private|public|protected|published)"
+ },
+ {
+ "include": "#function-declaration"
+ },
+ {
+ "include": "#property"
+ },
+ {
+ "include": "#declaration"
+ }
+ ]
+ },
+ "property": {
+ "name": "meta.property.pascal",
+ "begin": "(?i)\\b(property)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.pascal"
+ }
+ },
+ "end": ";",
+ "patterns": [
+ {
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)",
+ "captures": {
+ "1": {
+ "name": "variable.other.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#keywords"
+ },
+ {
+ "name": "entity.name.function.pascal",
+ "match": ".*"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)",
+ "captures": {
+ "1": {
+ "name": "keyword.pascal"
+ },
+ "2": {
+ "patterns": [
+ {
+ "include": "#expression"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "statement": {
+ "patterns": [
+ {
+ "include": "#statement-compound"
+ },
+ {
+ "include": "#expression"
+ }
+ ]
+ },
+ "expression": {
+ "patterns": [
+ {
+ "name": "constant.character.pascal",
+ "match": "(?i)#[0-9]+"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\$[0-9a-f]+\\b"
+ },
+ {
+ "name": "constant.numeric.pascal",
+ "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b"
+ },
+ {
+ "include": "#strings"
+ },
+ {
+ "include": "#keywords"
+ },
+ {
+ "include": "#identifier"
+ }
+ ]
+ },
+ "statement-compound": {
+ "name": "meta.section.pascal",
+ "begin": "(?i)\\b(begin|case|try)\\b",
+ "beginCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "end": "(?i)\\b(end)\\b",
+ "endCaptures": {
+ "1": {
+ "name": "keyword.control.pascal"
+ }
+ },
+ "patterns": [
+ {
+ "include": "#comment"
+ },
+ {
+ "include": "#asm"
+ },
+ {
+ "include": "#statement"
+ }
+ ]
+ },
+ "identifier": {
+ "patterns": [
+ {
+ "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(",
+ "captures": {
+ "1": {
+ "name": "entity.name.function.pascal"
+ }
+ }
+ },
+ {
+ "name": "variable.other.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)"
+ },
+ {
+ "name": "entity.name.class.pascal",
+ "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b"
+ }
+ ]
+ },
+ "keywords": {
+ "patterns": [
+ {
+ "name": "entity.name.type.pascal",
+ "match": "(?i)\\b(string)\\b"
+ },
+ {
+ "name": "keyword.control.pascal",
+ "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b"
+ },
+ {
+ "name": "constant.language.pascal",
+ "match": "(?i)\\b(true|false)\\b"
+ },
+ {
+ "name": "keyword.pascal",
+ "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b"
+ }
+ ]
+ },
+ "strings": {
+ "name": "string.quoted.pascal",
+ "begin": "'",
+ "end": "'(?!')",
+ "patterns": [
+ {
+ "name": "constant.character.escape.pascal",
+ "match": "''"
+ }
+ ]
+ }
+ },
+ "scopeName": "source.pascal"
+ }
\ No newline at end of file
| 779 | Merge pull request #198 from AlphaNecron/dev | 0 | .json | TextMate | mit | AvaloniaUI/AvaloniaEdit |
10067240 | <NME> theme.css
<BEF> .jsgrid-grid-header,
.jsgrid-grid-body,
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
.jsgrid-insert-row > .jsgrid-cell,
.jsgrid-edit-row > .jsgrid-cell {
border: 1px solid #e9e9e9;
}
.jsgrid-header-row > .jsgrid-header-cell {
border-top: 0;
border-top: 0;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-grid-header tr:last-child th,
.jsgrid-grid-header tr:last-child td {
border-bottom: none;
}
.jsgrid-header-row .jsgrid-header-sort {
}
.jsgrid-header-row > .jsgrid-header-cell:last-child,
.jsgrid-filter-row > .jsgrid-cell:last-child,
.jsgrid-insert-row > .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-header-row .jsgrid-align-right,
.jsgrid-header-row .jsgrid-align-left {
text-align: center;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-header-scrollbar {
scrollbar-arrow-color: #f1f1f1;
scrollbar-base-color: #f1f1f1;
scrollbar-3dlight-color: #f1f1f1;
scrollbar-highlight-color: #f1f1f1;
scrollbar-track-color: #f1f1f1;
scrollbar-shadow-color: #f1f1f1;
scrollbar-dark-shadow-color: #f1f1f1;
}
.jsgrid-header-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
.jsgrid-header-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
}
.jsgrid-header-sortable:hover {
cursor: pointer;
background: #fcfcfc;
}
.jsgrid-header-row .jsgrid-header-sort {
background: #c4e2ff;
}
.jsgrid-header-sort:before {
content: " ";
display: block;
float: left;
width: 0;
height: 0;
border-style: solid;
}
.jsgrid-header-sort-asc:before {
border-width: 0 5px 5px 5px;
border-color: transparent transparent #009a67 transparent;
}
.jsgrid-header-sort-desc:before {
border-width: 5px 5px 0 5px;
border-color: #009a67 transparent transparent transparent;
}
.jsgrid-grid-body {
border-top: none;
}
.jsgrid-cell {
border: #f3f3f3 1px solid;
}
.jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell,
.jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell {
border-top: none;
}
.jsgrid-grid-body .jsgrid-cell:first-child {
border-left: none;
}
.jsgrid-grid-body .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-alt-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-header-row > .jsgrid-header-cell {
background: #f9f9f9;
}
.jsgrid-filter-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-insert-row > .jsgrid-cell {
background: #e3ffe5;
}
.jsgrid-edit-row > .jsgrid-cell {
background: #fdffe3;
}
.jsgrid-selected-row > .jsgrid-cell {
background: #c4e2ff;
border-color: #c4e2ff;
}
.jsgrid-nodata-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-invalid input,
.jsgrid-invalid select,
.jsgrid-invalid textarea {
background: #ffe3e5;
border: 1px solid #ff808a;
}
.jsgrid-pager-current-page {
font-weight: bold;
}
.jsgrid-pager-nav-inactive-button a {
color: #d3d3d3;
}
.jsgrid-button + .jsgrid-button {
margin-left: 5px;
}
.jsgrid-button:hover {
opacity: .5;
transition: opacity 200ms linear;
}
.jsgrid .jsgrid-button {
width: 16px;
height: 16px;
border: none;
cursor: pointer;
background-image: url(icons.png);
background-repeat: no-repeat;
background-color: transparent;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) {
.jsgrid .jsgrid-button {
background-image: url(icons-2x.png);
background-size: 24px 352px;
}
}
.jsgrid .jsgrid-mode-button {
width: 24px;
height: 24px;
}
.jsgrid-mode-on-button {
opacity: .5;
}
.jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; }
.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; }
.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; }
.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; }
.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; }
.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; }
.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; }
.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; }
.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
.jsgrid-load-shader {
background: #ddd;
opacity: .5;
filter: alpha(opacity=50);
}
.jsgrid-load-panel {
width: 15em;
height: 5em;
background: #fff;
border: 1px solid #e9e9e9;
padding-top: 3em;
text-align: center;
}
.jsgrid-load-panel:before {
content: ' ';
position: absolute;
top: .5em;
left: 50%;
margin-left: -1em;
width: 2em;
height: 2em;
border: 2px solid #009a67;
border-right-color: transparent;
border-radius: 50%;
-webkit-animation: indicator 1s linear infinite;
animation: indicator 1s linear infinite;
}
@-webkit-keyframes indicator
{
from { -webkit-transform: rotate(0deg); }
50% { -webkit-transform: rotate(180deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes indicator
{
from { transform: rotate(0deg); }
50% { transform: rotate(180deg); }
to { transform: rotate(360deg); }
}
/* old IE */
.jsgrid-load-panel {
padding-top: 1.5em\9;
}
.jsgrid-load-panel:before {
display: none\9;
}
<MSG> Theme: Fix header row borders
<DFF> @@ -12,13 +12,12 @@
border-top: 0;
}
-.jsgrid-grid-header {
- background: #f9f9f9;
+.jsgrid-header-row > th, .jsgrid-filter-row > td, .jsgrid-insert-row > td {
+ border-bottom: 0;
}
-.jsgrid-grid-header tr:last-child th,
-.jsgrid-grid-header tr:last-child td {
- border-bottom: none;
+.jsgrid-grid-header {
+ background: #f9f9f9;
}
.jsgrid-header-row .jsgrid-header-sort {
| 4 | Theme: Fix header row borders | 5 | .css | css | mit | tabalinas/jsgrid |
10067241 | <NME> theme.css
<BEF> .jsgrid-grid-header,
.jsgrid-grid-body,
.jsgrid-header-row > .jsgrid-header-cell,
.jsgrid-filter-row > .jsgrid-cell,
.jsgrid-insert-row > .jsgrid-cell,
.jsgrid-edit-row > .jsgrid-cell {
border: 1px solid #e9e9e9;
}
.jsgrid-header-row > .jsgrid-header-cell {
border-top: 0;
border-top: 0;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-grid-header tr:last-child th,
.jsgrid-grid-header tr:last-child td {
border-bottom: none;
}
.jsgrid-header-row .jsgrid-header-sort {
}
.jsgrid-header-row > .jsgrid-header-cell:last-child,
.jsgrid-filter-row > .jsgrid-cell:last-child,
.jsgrid-insert-row > .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-header-row .jsgrid-align-right,
.jsgrid-header-row .jsgrid-align-left {
text-align: center;
}
.jsgrid-grid-header {
background: #f9f9f9;
}
.jsgrid-header-scrollbar {
scrollbar-arrow-color: #f1f1f1;
scrollbar-base-color: #f1f1f1;
scrollbar-3dlight-color: #f1f1f1;
scrollbar-highlight-color: #f1f1f1;
scrollbar-track-color: #f1f1f1;
scrollbar-shadow-color: #f1f1f1;
scrollbar-dark-shadow-color: #f1f1f1;
}
.jsgrid-header-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
.jsgrid-header-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
}
.jsgrid-header-sortable:hover {
cursor: pointer;
background: #fcfcfc;
}
.jsgrid-header-row .jsgrid-header-sort {
background: #c4e2ff;
}
.jsgrid-header-sort:before {
content: " ";
display: block;
float: left;
width: 0;
height: 0;
border-style: solid;
}
.jsgrid-header-sort-asc:before {
border-width: 0 5px 5px 5px;
border-color: transparent transparent #009a67 transparent;
}
.jsgrid-header-sort-desc:before {
border-width: 5px 5px 0 5px;
border-color: #009a67 transparent transparent transparent;
}
.jsgrid-grid-body {
border-top: none;
}
.jsgrid-cell {
border: #f3f3f3 1px solid;
}
.jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell,
.jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell {
border-top: none;
}
.jsgrid-grid-body .jsgrid-cell:first-child {
border-left: none;
}
.jsgrid-grid-body .jsgrid-cell:last-child {
border-right: none;
}
.jsgrid-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-alt-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-header-row > .jsgrid-header-cell {
background: #f9f9f9;
}
.jsgrid-filter-row > .jsgrid-cell {
background: #fcfcfc;
}
.jsgrid-insert-row > .jsgrid-cell {
background: #e3ffe5;
}
.jsgrid-edit-row > .jsgrid-cell {
background: #fdffe3;
}
.jsgrid-selected-row > .jsgrid-cell {
background: #c4e2ff;
border-color: #c4e2ff;
}
.jsgrid-nodata-row > .jsgrid-cell {
background: #fff;
}
.jsgrid-invalid input,
.jsgrid-invalid select,
.jsgrid-invalid textarea {
background: #ffe3e5;
border: 1px solid #ff808a;
}
.jsgrid-pager-current-page {
font-weight: bold;
}
.jsgrid-pager-nav-inactive-button a {
color: #d3d3d3;
}
.jsgrid-button + .jsgrid-button {
margin-left: 5px;
}
.jsgrid-button:hover {
opacity: .5;
transition: opacity 200ms linear;
}
.jsgrid .jsgrid-button {
width: 16px;
height: 16px;
border: none;
cursor: pointer;
background-image: url(icons.png);
background-repeat: no-repeat;
background-color: transparent;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) {
.jsgrid .jsgrid-button {
background-image: url(icons-2x.png);
background-size: 24px 352px;
}
}
.jsgrid .jsgrid-mode-button {
width: 24px;
height: 24px;
}
.jsgrid-mode-on-button {
opacity: .5;
}
.jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; }
.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; }
.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; }
.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; }
.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; }
.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; }
.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; }
.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; }
.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
.jsgrid-load-shader {
background: #ddd;
opacity: .5;
filter: alpha(opacity=50);
}
.jsgrid-load-panel {
width: 15em;
height: 5em;
background: #fff;
border: 1px solid #e9e9e9;
padding-top: 3em;
text-align: center;
}
.jsgrid-load-panel:before {
content: ' ';
position: absolute;
top: .5em;
left: 50%;
margin-left: -1em;
width: 2em;
height: 2em;
border: 2px solid #009a67;
border-right-color: transparent;
border-radius: 50%;
-webkit-animation: indicator 1s linear infinite;
animation: indicator 1s linear infinite;
}
@-webkit-keyframes indicator
{
from { -webkit-transform: rotate(0deg); }
50% { -webkit-transform: rotate(180deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes indicator
{
from { transform: rotate(0deg); }
50% { transform: rotate(180deg); }
to { transform: rotate(360deg); }
}
/* old IE */
.jsgrid-load-panel {
padding-top: 1.5em\9;
}
.jsgrid-load-panel:before {
display: none\9;
}
<MSG> Theme: Fix header row borders
<DFF> @@ -12,13 +12,12 @@
border-top: 0;
}
-.jsgrid-grid-header {
- background: #f9f9f9;
+.jsgrid-header-row > th, .jsgrid-filter-row > td, .jsgrid-insert-row > td {
+ border-bottom: 0;
}
-.jsgrid-grid-header tr:last-child th,
-.jsgrid-grid-header tr:last-child td {
- border-bottom: none;
+.jsgrid-grid-header {
+ background: #f9f9f9;
}
.jsgrid-header-row .jsgrid-header-sort {
| 4 | Theme: Fix header row borders | 5 | .css | css | mit | tabalinas/jsgrid |
10067242 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067243 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067244 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067245 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067246 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067247 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067248 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067249 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
&& !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
.GetAwaiter()
.GetResult());
args.Handled = true;
}
}
private static void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
string text;
try
{
text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
}
catch (Exception)
{
return;
}
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> fix paste from external app on linux.
<DFF> @@ -24,6 +24,7 @@ using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
+using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
@@ -469,26 +470,26 @@ namespace AvaloniaEdit.Editing
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
- && !string.IsNullOrEmpty(Application.Current.Clipboard.GetTextAsync()
- .GetAwaiter()
- .GetResult());
+ args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
- private static void OnPaste(object target, ExecutedRoutedEventArgs args)
+ private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- string text;
+ textArea.Document.BeginUpdate();
+
+ string text = null;
try
{
- text = Application.Current.Clipboard.GetTextAsync().GetAwaiter().GetResult();
+ text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
+ textArea.Document.EndUpdate();
return;
}
@@ -505,6 +506,8 @@ namespace AvaloniaEdit.Editing
textArea.Caret.BringCaretToView();
args.Handled = true;
+
+ textArea.Document.EndUpdate();
}
}
| 10 | fix paste from external app on linux. | 7 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.