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
|
---|---|---|---|---|---|---|---|---|
10059350 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059351 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059352 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059353 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059354 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059355 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059356 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059357 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059358 | <NME> MockGlyphTypeface.cs
<BEF> using Avalonia.Platform;
using System;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockGlyphTypeface : IGlyphTypefaceImpl
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
public short DesignEmHeight => DefaultFontSize;
public int Ascent => 2;
public int Descent => 10;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
public int StrikethroughPosition { get; }
public int StrikethroughThickness { get; }
public bool IsFixedPitch { get; }
public ushort GetGlyph(uint codepoint)
{
return 0;
}
public ushort[] GetGlyphs(ReadOnlySpan<uint> codepoints)
{
return new ushort[codepoints.Length];
}
public int GetGlyphAdvance(ushort glyph)
{
return GlyphAdvance;
}
public int[] GetGlyphAdvances(ReadOnlySpan<ushort> glyphs)
{
var advances = new int[glyphs.Length];
for (var i = 0; i < advances.Length; i++)
{
advances[i] = GlyphAdvance;
}
return advances;
}
public void Dispose() { }
}
}
<MSG> Added failing tests
<DFF> @@ -8,10 +8,12 @@ namespace AvaloniaEdit.AvaloniaMocks
{
public const int GlyphAdvance = 8;
public const short DefaultFontSize = 10;
+ public const int GlyphAscent = 2;
+ public const int GlyphDescent = 10;
public short DesignEmHeight => DefaultFontSize;
- public int Ascent => 2;
- public int Descent => 10;
+ public int Ascent => GlyphAscent;
+ public int Descent => GlyphDescent;
public int LineGap { get; }
public int UnderlinePosition { get; }
public int UnderlineThickness { get; }
| 4 | Added failing tests | 2 | .cs | Tests/AvaloniaMocks/MockGlyphTypeface | mit | AvaloniaUI/AvaloniaEdit |
10059359 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
return;
var errors = this._validation.validate($.extend({
value: item[field.name],
rules: field.validate
}, args));
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Validation: Fix getting item field for validation to support nested props
<DFF> @@ -1121,7 +1121,7 @@
return;
var errors = this._validation.validate($.extend({
- value: item[field.name],
+ value: this._getItemFieldValue(item, field),
rules: field.validate
}, args));
| 1 | Validation: Fix getting item field for validation to support nested props | 1 | .js | core | mit | tabalinas/jsgrid |
10059360 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
return;
var errors = this._validation.validate($.extend({
value: item[field.name],
rules: field.validate
}, args));
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Validation: Fix getting item field for validation to support nested props
<DFF> @@ -1121,7 +1121,7 @@
return;
var errors = this._validation.validate($.extend({
- value: item[field.name],
+ value: this._getItemFieldValue(item, field),
rules: field.validate
}, args));
| 1 | Validation: Fix getting item field for validation to support nested props | 1 | .js | core | mit | tabalinas/jsgrid |
10059361 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
A lightweight component layout engine for client and server.
FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/).
```js
// Define a module
var Apple = fruitmachine.define({
name: 'apple',
template: function(){ return 'hello' }
});
// Create a module
var apple = new Apple();
// Render it
apple.render();
apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
## Installation
- [Article viewer](http://wilsonpage.github.io/fruitmachine/examples/1a/)
- [TODO](http://wilsonpage.github.io/fruitmachine/examples/todo/)
## Contents
- [Introduction](https://github.com/wilsonpage/fruitmachine/tree/master/docs/introduction.md)
- [Getting started](https://github.com/wilsonpage/fruitmachine/tree/master/docs/getting-started.md)
$ bower install fruitmachine
```
or
Download the [pre-built version][built] (~2k gzipped).
[built]: http://wzrd.in/standalone/fruitmachine@latest
## Examples
- [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/)
- [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/)
## Documentation
- [Introduction](docs/introduction.md)
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Slots](docs/slots.md)
- [View assembly](docs/layout-assembly.md)
- [Instantiation](docs/module-instantiation.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [Rendering](docs/rendering.md)
- [DOM injection](docs/injection.md)
- [The module element](docs/module-el.md)
- [Queries](docs/queries.md)
- [Helpers](docs/module-helpers.md)
- [Removing & destroying](docs/removing-and-destroying.md)
- [Extending](docs/extending-modules.md)
- [Server-side rendering](docs/server-side-rendering.md)
- [API](docs/api.md)
- [Events](docs/events.md)
## Tests
#### With PhantomJS
```
$ npm install
$ npm test
```
#### Without PhantomJS
```
$ node_modules/.bin/buster-static
```
...then visit http://localhost:8282/ in browser
## Author
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
## Contributors
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
- **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews)
## License
Copyright (c) 2018 The Financial Times Limited
Licensed under the MIT license.
## Credits and collaboration
FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
<MSG> Updated docs
<DFF> @@ -26,7 +26,7 @@ apple.el.outerHTML;
- [Article viewer](http://wilsonpage.github.io/fruitmachine/examples/1a/)
- [TODO](http://wilsonpage.github.io/fruitmachine/examples/todo/)
-## Contents
+## Documentation
- [Introduction](https://github.com/wilsonpage/fruitmachine/tree/master/docs/introduction.md)
- [Getting started](https://github.com/wilsonpage/fruitmachine/tree/master/docs/getting-started.md)
| 1 | Updated docs | 1 | .md | md | mit | ftlabs/fruitmachine |
10059362 | <NME> es.js
<BEF> (function(jsGrid) {
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
deleteConfirm: "Esta seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
loadMessage: "Espere, por favor...",
invalidMessage: "Datos inválidos!"
},
loadIndicator: {
message: "Cargando..."
},
fields: {
control: {
searchModeButtonTooltip: "Cambia a búsqueda",
insertModeButtonTooltip: "Cambia a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
clearFilterButtonTooltip: "Borrar filtro",
insertButtonTooltip: "Insertar",
updateButtonTooltip: "Actualizar",
cancelEditButtonTooltip: "Cancelar edición"
}
},
validators: {
required: { message: "Campo requerido" },
rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
minLength: { message: "La longitud del valor esta demasiado largo" },
maxLength: { message: "La longitud del valor esta demasiado corto" },
pattern: { message: "Valor no coincide con el patrón definido" },
range: { message: "Valor fuera del intervalo definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
};
}(jsGrid, jQuery));
<MSG> Merge pull request #1 from julmarci/spanish_localization
Improved Spanish localization
<DFF> @@ -3,14 +3,14 @@
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
- deleteConfirm: "Esta seguro?",
+ deleteConfirm: "¿Está seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
- loadMessage: "Espere, por favor...",
- invalidMessage: "Datos inválidos!"
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "¡Datos no válidos!"
},
loadIndicator: {
@@ -19,8 +19,8 @@
fields: {
control: {
- searchModeButtonTooltip: "Cambia a búsqueda",
- insertModeButtonTooltip: "Cambia a inserción",
+ searchModeButtonTooltip: "Cambiar a búsqueda",
+ insertModeButtonTooltip: "Cambiar a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
@@ -33,11 +33,11 @@
validators: {
required: { message: "Campo requerido" },
- rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
- minLength: { message: "La longitud del valor esta demasiado largo" },
- maxLength: { message: "La longitud del valor esta demasiado corto" },
- pattern: { message: "Valor no coincide con el patrón definido" },
- range: { message: "Valor fuera del intervalo definido" },
+ rangeLength: { message: "La longitud del valor está fuera del intervalo definido" },
+ minLength: { message: "La longitud del valor es demasiado larga" },
+ maxLength: { message: "La longitud del valor es demasiado corta" },
+ pattern: { message: "El valor no se ajusta al patrón definido" },
+ range: { message: "Valor fuera del rango definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
| 10 | Merge pull request #1 from julmarci/spanish_localization | 10 | .js | js | mit | tabalinas/jsgrid |
10059363 | <NME> es.js
<BEF> (function(jsGrid) {
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
deleteConfirm: "Esta seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
loadMessage: "Espere, por favor...",
invalidMessage: "Datos inválidos!"
},
loadIndicator: {
message: "Cargando..."
},
fields: {
control: {
searchModeButtonTooltip: "Cambia a búsqueda",
insertModeButtonTooltip: "Cambia a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
clearFilterButtonTooltip: "Borrar filtro",
insertButtonTooltip: "Insertar",
updateButtonTooltip: "Actualizar",
cancelEditButtonTooltip: "Cancelar edición"
}
},
validators: {
required: { message: "Campo requerido" },
rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
minLength: { message: "La longitud del valor esta demasiado largo" },
maxLength: { message: "La longitud del valor esta demasiado corto" },
pattern: { message: "Valor no coincide con el patrón definido" },
range: { message: "Valor fuera del intervalo definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
};
}(jsGrid, jQuery));
<MSG> Merge pull request #1 from julmarci/spanish_localization
Improved Spanish localization
<DFF> @@ -3,14 +3,14 @@
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
- deleteConfirm: "Esta seguro?",
+ deleteConfirm: "¿Está seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
- loadMessage: "Espere, por favor...",
- invalidMessage: "Datos inválidos!"
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "¡Datos no válidos!"
},
loadIndicator: {
@@ -19,8 +19,8 @@
fields: {
control: {
- searchModeButtonTooltip: "Cambia a búsqueda",
- insertModeButtonTooltip: "Cambia a inserción",
+ searchModeButtonTooltip: "Cambiar a búsqueda",
+ insertModeButtonTooltip: "Cambiar a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
@@ -33,11 +33,11 @@
validators: {
required: { message: "Campo requerido" },
- rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
- minLength: { message: "La longitud del valor esta demasiado largo" },
- maxLength: { message: "La longitud del valor esta demasiado corto" },
- pattern: { message: "Valor no coincide con el patrón definido" },
- range: { message: "Valor fuera del intervalo definido" },
+ rangeLength: { message: "La longitud del valor está fuera del intervalo definido" },
+ minLength: { message: "La longitud del valor es demasiado larga" },
+ maxLength: { message: "La longitud del valor es demasiado corta" },
+ pattern: { message: "El valor no se ajusta al patrón definido" },
+ range: { message: "Valor fuera del rango definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
| 10 | Merge pull request #1 from julmarci/spanish_localization | 10 | .js | js | mit | tabalinas/jsgrid |
10059364 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059365 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059366 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059367 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059368 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059369 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059370 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059371 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059372 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059373 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059374 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059375 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059376 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059377 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059378 | <NME> TextEditorModel.cs
<BEF> using System;
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
private ITextSource _textSource;
private LineRanges _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
{
_textView = textView;
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
_lineRanges = new LineRanges(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
UpdateSnapshot();
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
private void UpdateSnapshot()
{
lock (_lock)
{
_textSource = _document.CreateSnapshot();
}
}
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
_lineRanges.Update(e);
}
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
InvalidateLineRange(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}
public override int GetNumberOfLines()
{
return _documentSnapshot.LineCount;
}
public override string GetLineText(int lineIndex)
{
return _documentSnapshot.GetLineText(lineIndex);
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
}
UpdateLineRanges(e);
UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
{
lock (_lock)
{
var lineRange = _lineRanges.Get(lineIndex);
return _textSource.GetText(lineRange.Offset, lineRange.Length);
}
}
{
lock (_lock)
{
return _lineRanges.Get(lineIndex).Length;
}
}
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (!_textView.VisualLinesValid ||
_textView.VisualLines.Count == 0)
return;
ForceTokenization(
_textView.VisualLines[0].FirstDocumentLine.LineNumber - 1,
_textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1);
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Convert the line ranges object to a document snaphost
<DFF> @@ -16,8 +16,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextDocument _document;
private readonly TextView _textView;
private volatile int _lineCount;
- private ITextSource _textSource;
- private LineRanges _lineRanges;
+ private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -27,32 +26,22 @@ namespace AvaloniaEdit.TextMate
_exceptionHandler = exceptionHandler;
_lineCount = _document.LineCount;
- _lineRanges = new LineRanges(_document);
+ _documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _lineCount; i++)
AddLine(i);
- UpdateSnapshot();
-
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
- private void UpdateSnapshot()
- {
- lock (_lock)
- {
- _textSource = _document.CreateSnapshot();
- }
- }
-
private void UpdateLineRanges(DocumentChangeEventArgs e)
{
lock (_lock)
{
_lineCount = _document.LineCount;
- _lineRanges.Update(e);
+ _documentSnapshot.Update(e);
}
}
@@ -131,7 +120,6 @@ namespace AvaloniaEdit.TextMate
}
UpdateLineRanges(e);
- UpdateSnapshot();
// invalidate the changed line it's previous line
// some grammars (JSON, csharp, ...)
@@ -158,8 +146,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- var lineRange = _lineRanges.Get(lineIndex);
- return _textSource.GetText(lineRange.Offset, lineRange.Length);
+ return _documentSnapshot.GetLineText(lineIndex);
}
}
@@ -167,7 +154,7 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- return _lineRanges.Get(lineIndex).Length;
+ return _documentSnapshot.GetLineLength(lineIndex);
}
}
}
| 5 | Convert the line ranges object to a document snaphost | 18 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10059379 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059380 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059381 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059382 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059383 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059384 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059385 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059386 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059387 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059388 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059389 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059390 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059391 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059392 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059393 | <NME> RoutedCommand.cs
<BEF> using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Avalonia;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit
{
public class RoutedCommand : ICommand
{
public string Name { get; }
public KeyGesture Gesture { get; }
public RoutedCommand(string name, KeyGesture keyGesture = null)
{
Name = name;
Gesture = keyGesture;
}
static RoutedCommand()
{
CanExecuteEvent.AddClassHandler<IRoutedCommandBindable>(CanExecuteEventHandler);
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
{
return args =>
{
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
args.CanExecute = binding != null;
};
}
private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
{
return args =>
{
// ReSharper disable once UnusedVariable
var binding = control.CommandBindings.Where(c => c != null)
.FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
};
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public bool CanExecute(object parameter, IInputElement target)
{
if (target == null) return false;
var args = new CanExecuteRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
return args.CanExecute;
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter, Application.Current.FocusManager.Current);
}
public static RoutedEvent<ExecutedRoutedEventArgs> ExecutedEvent { get; } = RoutedEvent.Register<ExecutedRoutedEventArgs>(nameof(ExecutedEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
public void Execute(object parameter, IInputElement target)
{
if (target == null) return;
var args = new ExecutedRoutedEventArgs(this, parameter);
target.RaiseEvent(args);
}
void ICommand.Execute(object parameter)
{
Execute(parameter, Application.Current.FocusManager.Current);
}
// TODO
event EventHandler ICommand.CanExecuteChanged
{
add { }
remove { }
}
}
public interface IRoutedCommandBindable : IInteractive
{
IList<RoutedCommandBinding> CommandBindings { get; }
}
public class RoutedCommandBinding
{
public RoutedCommandBinding(RoutedCommand command,
EventHandler<ExecutedRoutedEventArgs> executed = null,
EventHandler<CanExecuteRoutedEventArgs> canExecute = null)
{
Command = command;
if (executed != null) Executed += executed;
if (canExecute != null) CanExecute += canExecute;
}
public RoutedCommand Command { get; }
public event EventHandler<CanExecuteRoutedEventArgs> CanExecute;
public event EventHandler<ExecutedRoutedEventArgs> Executed;
internal bool DoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (e.Handled) return true;
var canExecute = CanExecute;
if (canExecute == null)
{
if (Executed != null)
{
e.Handled = true;
e.CanExecute = true;
}
}
else
{
canExecute(sender, e);
if (e.CanExecute)
{
e.Handled = true;
}
}
return e.CanExecute;
}
internal bool DoExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (!e.Handled)
{
var executed = Executed;
if (executed != null)
{
if (DoCanExecute(sender, new CanExecuteRoutedEventArgs(e.Command, e.Parameter)))
{
executed(sender, e);
e.Handled = true;
return true;
}
}
}
return false;
}
}
public sealed class CanExecuteRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
public bool CanExecute { get; set; }
internal CanExecuteRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.CanExecuteEvent;
}
}
public sealed class ExecutedRoutedEventArgs : RoutedEventArgs
{
public ICommand Command { get; }
public object Parameter { get; }
internal ExecutedRoutedEventArgs(ICommand command, object parameter)
{
Command = command ?? throw new ArgumentNullException(nameof(command));
Parameter = parameter;
RoutedEvent = RoutedCommand.ExecutedEvent;
}
}
}
<MSG> fix obsolete
<DFF> @@ -25,24 +25,18 @@ namespace AvaloniaEdit
ExecutedEvent.AddClassHandler<IRoutedCommandBindable>(ExecutedEventHandler);
}
- private static Action<CanExecuteRoutedEventArgs> CanExecuteEventHandler(IRoutedCommandBindable control)
+ private static void CanExecuteEventHandler(IRoutedCommandBindable control, CanExecuteRoutedEventArgs args)
{
- return args =>
- {
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
- args.CanExecute = binding != null;
- };
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoCanExecute(control, args));
+ args.CanExecute = binding != null;
}
- private static Action<ExecutedRoutedEventArgs> ExecutedEventHandler(IRoutedCommandBindable control)
+ private static void ExecutedEventHandler(IRoutedCommandBindable control, ExecutedRoutedEventArgs args)
{
- return args =>
- {
- // ReSharper disable once UnusedVariable
- var binding = control.CommandBindings.Where(c => c != null)
- .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
- };
+ // ReSharper disable once UnusedVariable
+ var binding = control.CommandBindings.Where(c => c != null)
+ .FirstOrDefault(c => c.Command == args.Command && c.DoExecuted(control, args));
}
public static RoutedEvent<CanExecuteRoutedEventArgs> CanExecuteEvent { get; } = RoutedEvent.Register<CanExecuteRoutedEventArgs>(nameof(CanExecuteEvent), RoutingStrategies.Bubble, typeof(RoutedCommand));
| 8 | fix obsolete | 14 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059394 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059395 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059396 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059397 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059398 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059399 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059400 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059401 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059402 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059403 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059404 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059405 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059406 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059407 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059408 | <NME> TextEditor.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.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used 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;
/// <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 TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
SearchPanel.Install(this);
}
/// <summary>
searchPanel = SearchPanel.Install(this);
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
}
private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Expose the search panel from the TextEditor
<DFF> @@ -282,14 +282,15 @@ namespace AvaloniaEdit
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
-
+ private SearchPanel searchPanel;
+
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
- SearchPanel.Install(this);
+ searchPanel = SearchPanel.Install(this);
}
/// <summary>
@@ -297,6 +298,11 @@ namespace AvaloniaEdit
/// </summary>
public TextArea TextArea => textArea;
+ /// <summary>
+ /// Gets the search panel.
+ /// </summary>
+ public SearchPanel SearchPanel => searchPanel;
+
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
| 8 | Expose the search panel from the TextEditor | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059409 | <NME> events.md
<BEF> ## Events
Events are at the core of fruitmachine. They allows us to decouple View interactions from one another. By default *FruitMachine* fires the following events on View module 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
- `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> Merge pull request #77 from ftlabs/before-x
Add more docs for events - addresses #70
<DFF> @@ -2,10 +2,15 @@
Events are at the core of fruitmachine. They allows us to decouple View interactions from one another. By default *FruitMachine* fires the following events on View module instances:
+- `before initialize` Before the module is instantiated
- `initialize` On instantiation
+- `before setup` Before the module is setup
- `setup` When `.setup()` is called (remember 'setup' is recursive)
+- `before teardown` Before the module is torn down
- `teardown` When `.teardown()` or `.destroy()` are called (remember 'destroy' calls 'teardown' which recurses)
+- `before destroy` Before the module is destroyed
- `destroy` When `.setup()` is called (remember 'teardown' recurses)
+- `before tohtml` Before toHTML is called. `render` events are only fired on the node being rendered - not any of the children so if you want to manipulate a module's data model prior to rendering, hook into this event)
- `render` When `.render()` is called
#### Bubbling
| 5 | Merge pull request #77 from ftlabs/before-x | 0 | .md | md | mit | ftlabs/fruitmachine |
10059410 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059411 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059412 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059413 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059414 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059415 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059416 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059417 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059418 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059419 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059420 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059421 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059422 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059423 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059424 | <NME> IndentationReformatter.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.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Merge branch 'fixes/csharp-indentation-strategy' into features/build-scripts | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059425 | <NME> .gitignore
<BEF> /old
.DS_Store
node_modules
npm-debug.log
artwork
coverage
<MSG> Tidy .gitignore
<DFF> @@ -1,4 +1,3 @@
-/old
.DS_Store
node_modules
npm-debug.log
| 0 | Tidy .gitignore | 1 | gitignore | mit | ftlabs/fruitmachine |
|
10059426 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059427 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059428 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059429 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059430 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059431 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059432 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059433 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059434 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059435 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059436 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059437 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059438 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059439 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059440 | <NME> TextEditorModelTests.cs
<BEF> 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();
using var 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", 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();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", 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();
using var 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", 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();
using var 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();
using var 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();
using var 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();
using var 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);
}
}
}
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
[Test]
public void Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
[Test]
public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npuppy\npuppy";
document.BeginUpdate();
document.Insert(0, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 1");
Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 1");
document.BeginUpdate();
document.Insert(7, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 2");
Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 2");
document.Insert(14, "*");
Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
"Wrong InvalidRange.StartLine 3");
Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
"Wrong InvalidRange.EndLine 3");
document.EndUpdate();
Assert.IsNotNull(textEditorModel.InvalidRange,
"InvalidRange should not be null");
document.EndUpdate();
Assert.IsNull(textEditorModel.InvalidRange,
"InvalidRange should be null");
Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
}
}
}
<MSG> Do not update ranges when replacing text of the same len
<DFF> @@ -205,5 +205,21 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual(document.LineCount, count);
}
+
+ [Test]
+ public void Remove_Text_Of_Same_Length_Should_Update_Line_Content()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ TextEditorModel textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npussy\nbirdie";
+
+ document.Replace(0, 1, "P");
+
+ Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0));
+ }
}
}
| 16 | Do not update ranges when replacing text of the same len | 0 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059441 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059442 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059443 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059444 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059445 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059446 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059447 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059448 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10059449 | <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();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
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.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;
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
_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");
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine => visualLine.TextRunProperties.Underline = true);
}
if (indexOfStrikeThrough != -1)
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine => visualLine.TextRunProperties.Strikethrough = true);
}
}
}
}
}
}
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 Demo text decorations
<DFF> @@ -40,20 +40,20 @@ namespace AvaloniaEdit.Demo
public MainWindow()
{
-
+
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.ContextMenu = new ContextMenu
- {
- Items = new List<MenuItem>
- {
+ _textEditor.ContextMenu = new ContextMenu
+ {
+ Items = new List<MenuItem>
+ {
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;
@@ -107,7 +107,7 @@ namespace AvaloniaEdit.Demo
private void Caret_PositionChanged(object sender, EventArgs e)
{
- _statusTextBlock.Text = string.Format("Line {0} Column {1}",
+ _statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
@@ -260,7 +260,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
- visualLine => visualLine.TextRunProperties.Underline = true);
+ 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)
@@ -268,7 +281,20 @@ namespace AvaloniaEdit.Demo
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
- visualLine => visualLine.TextRunProperties.Strikethrough = true);
+ 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);
+ }
+ }
+ );
}
}
}
| 35 | Fix Demo text decorations | 9 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.