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
10064050
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064051
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064052
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064053
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064054
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064055
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064056
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064057
<NME> AvaloniaEdit.sln <BEF>  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32112.339 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit", "src\AvaloniaEdit\AvaloniaEdit.csproj", "{4B04026F-BA96-4721-AE28-0970CB5806A9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Demo", "src\AvaloniaEdit.Demo\AvaloniaEdit.Demo.csproj", "{03763F37-9BD9-4D1D-ADC9-1050F6F8C062}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.Tests", "test\AvaloniaEdit.Tests\AvaloniaEdit.Tests.csproj", "{9E5D4372-D362-44A2-984D-578288870AB8}" EndProject 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 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU 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> Removed unwanted csproj file in solution <DFF> @@ -18,8 +18,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AvaloniaEdit.TextMate", "src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj", "{63826C17-C08C-4E5F-AABB-443EBA565E92}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextMateSharp", "..\..\source\repos\TextMateSharp\src\TextMateSharp\TextMateSharp.csproj", "{BE42F73D-27CB-4630-8177-FAEE7B2BDAF7}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU
0
Removed unwanted csproj file in solution
2
.sln
sln
mit
AvaloniaUI/AvaloniaEdit
10064058
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064059
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064060
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064061
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064062
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064063
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064064
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064065
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064066
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064067
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064068
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064069
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064070
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064071
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064072
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. and many,many more! ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2 Update readme <DFF> @@ -13,6 +13,28 @@ AvaloniaEdit supports features like: and many,many more! +AvaloniaEdit currently consists of 3 packages + * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. + * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. + * [AvaloniaEdit.TextMate.Grammars](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) grammars for TextMate and additional infrastructure that helps you to use them. + + ### How to set up theme and syntax highlighting for my project? +First of all, if you want to use grammars that we support you should install [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate.Grammars/) with them and [package](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) with TextMate integration otherwise you just install the package with TextMate integration and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled. +```csharp +//First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. +var _textEditor = this.FindControl<TextEditor>("Editor"); + +//Here we initialize RegistryOptions with the theme we want to use. +var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); + +//Initial setup of TextMate. +var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); + +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. +//And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! +_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); +``` + ![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png)
22
Merge pull request #197 from AvaloniaUI/Takoooooo-patch-2
0
.md
md
mit
AvaloniaUI/AvaloniaEdit
10064073
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064074
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064075
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064076
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064077
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064078
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064079
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064080
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064081
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064082
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064083
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064084
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064085
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064086
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064087
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); return null; } public StreamReader GetInputStream(string scopeName) { return new StreamReader(GetFilePath(scopeName)); } public IRawTheme GetTheme() new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> fix interface implementation. <DFF> @@ -45,9 +45,9 @@ namespace AvaloniaEdit.Demo return null; } - public StreamReader GetInputStream(string scopeName) + public Stream GetInputStream(string scopeName) { - return new StreamReader(GetFilePath(scopeName)); + return File.OpenRead(GetFilePath(scopeName)); } public IRawTheme GetTheme()
2
fix interface implementation.
2
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10064088
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064089
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064090
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064091
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064092
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064093
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064094
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064095
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064096
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064097
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064098
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064099
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064100
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064101
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064102
<NME> TextEditorModelTests.cs <BEF> ADDFILE <MSG> Implemented unit tests <DFF> @@ -0,0 +1,209 @@ +using AvaloniaEdit.Document; +using AvaloniaEdit.Rendering; +using AvaloniaEdit.TextMate; + +using NUnit.Framework; + +namespace AvaloniaEdit.Tests.TextMate +{ + [TestFixture] + internal class TextEditorModelTests + { + [Test] + public void Lines_Should_Have_Valid_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + } + + [Test] + public void Lines_Should_Have_Valid_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Content() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); + } + + [Test] + public void Editing_Line_Should_Update_The_Line_Length() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + } + + [Test] + public void Inserting_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); + } + + [Test] + public void Removing_Line_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\r\npussy\r\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); + } + + [Test] + public void Document_Lines_Count_Should_Match_Model_Lines_Count() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "cutty "); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Insert_Document_Line_Should_Insert_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Insert(0, "lion\n"); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + + [Test] + public void Remove_Document_Line_Should_Remove_Model_Line() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + + document.Remove( + document.Lines[0].Offset, + document.Lines[0].TotalLength); + + int count = 0; + textEditorModel.ForEach((m) => count++); + + Assert.AreEqual(document.LineCount, count); + } + } +}
209
Implemented unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064103
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064104
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064105
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064106
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064107
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064108
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064109
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064110
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064111
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064112
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064113
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064114
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064115
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064116
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064117
<NME> TextArea.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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; foreach(var margin in LeftMargins) { margin.InvalidateVisual(); } } } { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> remove invalidation of margins manually. <DFF> @@ -1087,11 +1087,6 @@ namespace AvaloniaEdit.Editing TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight)); _offset = value; - - foreach(var margin in LeftMargins) - { - margin.InvalidateVisual(); - } } }
0
remove invalidation of margins manually.
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064118
<NME> History.md <BEF> 0.5.1 / 2013-05-20 ================== * change all descendant `model.el` properties set at `Module#render()` * change expose `fruitmachine.Events` * remove `Module#inDOM()` 0.5.0 / 2013-05-20 ================== * add support for third party models * change `fruitmachine.View` => `fruitmachine.Module` * change component.json to bower.json 0.4.2 / 2013-05-20 ================== * change allow `name` key as an alternative to `module` in module definitions 0.4.1 / 2013-05-17 ================== * fix bug with delegate event listeners not being passed correct aguments 0.4.0 / 2013-05-17 ================== * change `slot` now defines placement over `id` * change `children` can now be an object (keys as `slot`) or an array. * change `id` is optional, used only for queries. * change 'LazyViews' can only be instantiated `var view = fruitmachine(layout)` no longer via `fruitmachine.View`. * add event hooks on `View` for `'tojson'` and `'inflation'` * add events to `fruitmachine` namespace to allow `fruitmachine.on('inflation')` <MSG> Fix dates <DFF> @@ -1,11 +1,11 @@ -0.5.1 / 2013-05-20 +0.5.1 / 2013-05-22 ================== * change all descendant `model.el` properties set at `Module#render()` * change expose `fruitmachine.Events` * remove `Module#inDOM()` -0.5.0 / 2013-05-20 +0.5.0 / 2013-05-22 ================== * add support for third party models
2
Fix dates
2
.md
md
mit
ftlabs/fruitmachine
10064119
<NME> events.md <BEF> # Events Events are at the core of FruitMachine. They allows us to decouple View interactions from one another. FruitMachine events are interesting as they propagate (or bubble) up the view chain. This means that parents Views way up the view chain can still listen to events that happen in deeply nested View modules. ### Example ```js var Apple = FruitMachine.define({ - `destroy` When `.destroy()` is called (remember 'teardown' recurses) #### Bubbling FruitMachine events are interesting as they propagate (or bubble) up the view chain. This means that parent Views way up the view chain can still listen to events that happen in deeply nested View modules. This is useful because it means your app's controllers can listen and decide what to do when specific things happen within your views. The response logic doesn't have to be in the view module itself, meaning modules are decoupled from your app, and easily reused elsewhere. ```js var layout = new Layout(); var apple = new Apple(); layout.add(apple); layout.on('shout', function() { alert('layout heard apple shout'); }); apple.fire('shout'); //=> alert 'layout heard apple shout' ``` The FruitMachine default events (eg `initialize`, `setup`, `teardown`) do not bubble. #### Passing parameters ```js var layout = new Layout(); var apple = new Apple(); layout.add(apple); layout.on('shout', function(param) { alert('layout heard apple shout ' + param); }); apple.fire('shout', 'hello'); // alert - 'layout heard apple shout hello' ``` #### Listening only for specific modules ```js var layout = new Layout(); var apple = new Apple(); var orange = new Orange(); layout .add(apple) .add(orange); layout.on('shout', 'apple', function() { alert('layout heard apple shout'); }); apple.fire('shout'); //=> alert 'layout heard apple shout' orange.fire('shout'); //=> nothing ``` #### Utilising the event object The event object can be found on under `this.event`. It holds a reference to the target view, where the event originated. ```js var layout = new Layout(); var apple = new Apple(); var orange = new Orange(); layout .add(apple) .add(orange); layout.on('shout', function() { var module = this.event.target.module(); alert('layout heard ' + module + ' shout'); }); apple.fire('shout'); //=> alert 'layout heard apple shout' orange.fire('shout'); //=> alert 'layout heard orange shout' ``` It also allows you to stop the event propagating (bubbling) up the view by calling `this.event.stopPropagation()`, just like DOM events! ```js var layout = new Layout(); var apple = new Apple(); var orange = new Orange(); layout .add(apple) .add(orange); layout.on('shout', function() { alert('layout heard apple shout'); }); apple.on('shout', function() { this.event.stopPropagation(); /* 1 */ }); apple.fire('shout'); //=> nothing ``` 1. *By stopping propagation here, we stop the event from ever reaching the parent view `layout`, and thus the alert is never fired.* <MSG> Update events.md <DFF> @@ -1,9 +1,16 @@ - # Events -Events are at the core of FruitMachine. They allows us to decouple View interactions from one another. FruitMachine events are interesting as they propagate (or bubble) up the view chain. This means that parents Views way up the view chain can still listen to events that happen in deeply nested View modules. +Events are at the core of FruitMachine. They allows us to decouple View interactions from one another. By default *FruitMachine* fire the following events on View moudle instances: + +- `initialize` On instantiation +- `setup` When `.setup()` is called (remember 'setup' is recursive) +- `teardown` When `.teardown()` or `.destroy()` are called (remember 'destroy' calls 'teardown' which recurses) +- `destroy` When `.setup()` is called (remember 'teardown' recurses) +- `render` When `.render()` is called + +### Bubbling -### Example +FruitMachine events are interesting as they propagate (or bubble) up the view chain. This means that parents Views way up the view chain can still listen to events that happen in deeply nested View modules. ```js var Apple = FruitMachine.define({
10
Update events.md
3
.md
md
mit
ftlabs/fruitmachine
10064120
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064121
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064122
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064123
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064124
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064125
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064126
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064127
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064128
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064129
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064130
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064131
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064132
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064133
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064134
<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; using System.Threading.Tasks; 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) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } 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); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); 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; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge pull request #168 from alluLinger/master Ignore empty line copy <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { 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); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge pull request #168 from alluLinger/master
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064135
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064136
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064137
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064138
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064139
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064140
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064141
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064142
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064143
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064144
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064145
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064146
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064147
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064148
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064149
<NME> TextEditorOptions.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.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; OnPropertyChanged(nameof(RequireControlModifierForHyperlinkClick)); } } } /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument private int _indentationSize = 4; /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls <DFF> @@ -325,7 +325,7 @@ namespace AvaloniaEdit /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. - /// The default value is false; but it a good idea to set this property to true when using folding. + /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument
1
Merge branch 'master' into fix-avaloniaedit-on-hiding-external-controls
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit