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
|
---|---|---|---|---|---|---|---|---|
10066750 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
Assembles dynamic views on the client and server
## Getting Started
### On the server
Install the module with: `npm install fruitmachine`
```javascript
var fruitmachine = require('fruitmachine');
fruitmachine.awesome(); // "awesome"
```
### In the browser
Download the [production version][min] or the [development version][max].
[min]: https://raw.github.com/wilsonpage/fruitmachine/master/dist/fruitmachine.min.js
[max]: https://raw.github.com/wilsonpage/fruitmachine/master/dist/fruitmachine.js
In your web page:
```html
<script src="dist/fruitmachine.min.js"></script>
<script>
awesome(); // "awesome"
</script>
```
In your code, you can attach fruitmachine's methods to any object.
```html
<script>
this.exports = Bocoup.utils;
</script>
<script src="dist/fruitmachine.min.js"></script>
<script>
Bocoup.utils.awesome(); // "awesome"
</script>
```
## Documentation
_(Coming soon)_
## Examples
_(Coming soon)_
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](http://gruntjs.com/).
_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_
## Release History
_(Nothing yet)_
## License
Copyright (c) 2012 Wilson Page
Licensed under the MIT license.
// Render it
apple.render();
apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
## Installation
```
$ npm install fruitmachine
```
or
```
$ 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 readme
<DFF> @@ -2,56 +2,15 @@
Assembles dynamic views on the client and server
-## Getting Started
-### On the server
-Install the module with: `npm install fruitmachine`
-
-```javascript
-var fruitmachine = require('fruitmachine');
-fruitmachine.awesome(); // "awesome"
-```
-
-### In the browser
-Download the [production version][min] or the [development version][max].
-
-[min]: https://raw.github.com/wilsonpage/fruitmachine/master/dist/fruitmachine.min.js
-[max]: https://raw.github.com/wilsonpage/fruitmachine/master/dist/fruitmachine.js
-
-In your web page:
-
-```html
-<script src="dist/fruitmachine.min.js"></script>
-<script>
-awesome(); // "awesome"
-</script>
-```
-
-In your code, you can attach fruitmachine's methods to any object.
-
-```html
-<script>
-this.exports = Bocoup.utils;
-</script>
-<script src="dist/fruitmachine.min.js"></script>
-<script>
-Bocoup.utils.awesome(); // "awesome"
-</script>
-```
-
## Documentation
_(Coming soon)_
## Examples
_(Coming soon)_
-## Contributing
-In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](http://gruntjs.com/).
-
-_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_
-
## Release History
_(Nothing yet)_
## License
-Copyright (c) 2012 Wilson Page
+Copyright (c) 2012 Wilson Page
Licensed under the MIT license.
| 1 | Updated readme | 42 | .md | md | mit | ftlabs/fruitmachine |
10066751 | <NME> fruitmachine.js
<BEF> (function(root) {
'use strict';
var FruitMachine = typeof exports === 'object' ? exports : root['FruitMachine'] = {};
// Current Version
FruitMachine.VERSION = '0.0.1';
/**
* Turn on for debug messages.
*
* @constant
* @type {Boolean|Number}
*/
var debug = 0;
/**
* SETTINGS
*/
var SETTINGS = FruitMachine.SETTINGS = {
breakpointDebounce: 50,
slotClass: 'js-module',
moduleIdAttr: 'data-module-id',
moduleTypeAttr: 'data-module-type',
moduleDataAttr: 'data-model-data',
moduleParentAttr: 'data-parent',
mustacheSlotVarPrefix: 'module',
mustacheSlotArrayName: 'modules'
};
var templates = {};
// User must define their templates before creating any Models or Views.
var setTemplates = FruitMachine['templates'] = function(params) {
util.extend(templates, params);
};
// Create local references to some native methods.
var slice = Array.prototype.slice;
var splice = Array.prototype.splice;
var forEach = Array.prototype.forEach;
// An object that you can store your extended View classes in under module type.
FruitMachine.Views = {};
/**
attributes: function(attributes) {
var list = [];
for (var key in attributes) {
list.push(key + "='" + attributes[key] + "'");
}
return list.join(' ');
},
unescape: window.unescape,
extend: function(original) {
// Loop over every argument after the first.
slice.call(arguments, 1).forEach(function(source) {
for (var prop in source) {
return original;
},
inherits: function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
util.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
util.ctor.prototype = parent.prototype;
child.prototype = new util.ctor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) util.extend(child.prototype, protoProps);
// Add static properties to the constructor function, if supplied.
if (staticProps) util.extend(child, staticProps);
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
return child;
},
insertChild: function(child, parent, index) {
}
},
/**
* Replaces the contents of the one node with contents
* of another.
return function(prefix) {
return (prefix || '') + (counter++) + '_' + Math.round(Math.random() * 100000);
};
})()
};
// Backbone.Events
// -----------------
// Regular expression used to split event strings
var eventSplitter = /\s+/;
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback functions
// to an event; trigger`-ing an event fires all callbacks in succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = {
// Bind one or more space separated events, `events`, to a `callback`
var calls, event, node, tail, list;
if (!callback) return this;
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
while (event = events.shift()) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {tail: tail, next: list ? list.next : node};
}
return this;
// Loop through the listed events and contexts, splicing them out of the
// linked list of callbacks if appropriate.
events = events ? events.split(eventSplitter) : Object.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) return this;
all = calls.all;
events = events.split(eventSplitter);
rest = slice.call(arguments, 1);
// For each event, walk through the linked list of callbacks twice,
node.callback.apply(node.context || this, rest);
}
}
if (node = all) {
tail = node.tail;
args = [event].concat(rest);
* VIEW
*/
var viewOptions = ['module', 'el', 'parent', '_globals'];
var View = FruitMachine['View'] = function(options) {
// Use a custom extended class if it exists for this module type
// else use the default base view class.
var Constructor = FruitMachine.Views[options.module] || DefaultView;
return new Constructor(options);
};
var DefaultView = function(options) {
if (debug) console.log('Creating new view instance...');
var domChildren, i, l;
this._configure(options);
// Save a reference to this model in the globals.
this._globals.id[this._id] = this;
// Don't look for module nodes in the view element if we have flagged not to.
// When we initiate children we don't want to as the parent will have detected
// all module nodes already when the master View was instantiated.
if (!options.skipFindModuleNodes) {
this._globals.dom = this._getDomChildren();
}
// Find any DOM children with this parent
domChildren = this._globals.dom.byParent && this._globals.dom.byParent[this._id];
// First we create View instances for each child found in the DOM.
//
// This loop is for creating views from children which *have* DOM context.
if (domChildren) {
for (i = 0, l = domChildren.length; i < l; i++) {
this._add(domChildren[i]);
}
}
// ...then we create View instances for each child in the definition.
// The internal _add method wont add a child if one already exists on
// the parent with the same _id.
//
// This loop is for creating fresh child views with *no* DOM context.
if (options.children) {
for (i = 0, l = options.children.length; i < l; i++) {
this._add(options.children[i]);
util.extend(DefaultView.prototype, Events, {
_configure: function(options) {
this.parent = options.parent;
* Public Methods
*/
// Fired when a View is instantiated, overwrite this yourself.
initialize: function() {},
_add: function(options) {
var hasChild = !!this._childHash[options._id || options.id];
if (hasChild) return;
options._globals = this._globals;
options.skipFindModuleNodes = true;
this.add(new View(options), { append: false });
},
add: function(view, options) {
var at = options && options.at;
var append = options && options.append;
if (debug) console.log('Adding view...');
// Merge the global variable stores.
util.extend(this._globals.id, view._globals.id);
this._childHash[view.module] = this._childHash[view.module] || [];
this._childHash[view.module].push(view);
if (append !== false && view.el) {
util.insertChild(view.el, this.el, at);
}
// Return the newly created view.
return this;
},
remove: function(view, options) {
},
render: function(options) {
var html = this._toHTML(options);
var el, domChildren;
if (options && options.asString) return html;
// view element is not replaced, and we don't loose any delegate
// event listeners.
el = util.toNode(html);
if (this.el) util.replaceContent(el, this.el);
this.el = el;
// Update the View.els for each child View.
this.updateChildEls();
this.trigger('render');
if (debug) console.log('View instance rendered.');
// Return this for chaining.
return this;
},
updateChildEls: function() {
var domChildren = this._getDomChildren().all;
for (var i = 0, l = domChildren.length; i < l; i++) {
var child = domChildren[i];
this.id(child._id).el = child.el;
}
return this;
},
get: function(key) {
return key ? (this[key] || this._data[key]) : this._data;
},
set: function(data, val) {
if (typeof data === 'string') {
this._data[data] = val;
} else {
util.extend(this._data, data);
}
return this;
},
child: function(query) {
var result = this._childHash[query];
return result[0] || result;
},
children: function(query) {
return this._childHash[query];
},
id: function(id) {
return id ? this._globals.id[id] : this._id;
},
inject: function(el) {
if (!el) return this;
el.innerHTML = '';
return this;
},
setup: function() {
if (debug) console.log('Setting up view...');
// Call 'setup' on all subviews first (bottom up recursion).
for (var i = 0, l = this._children.length; i < l; i++) {
this._children[i].setup();
}
// We don't want to run setup on a module more than once, right?
if (this.isSetup) return this;
// We trigger a 'setup' event that you can bind to
// inside you custom Views to perform any setup logic.
this.trigger('setup');
// Flag as setup
this.isSetup = true;
},
_detach: function(options) {
var i;
var skipEl = options && options.skipEl;
return this;
},
destroy: function(options) {
var detach = options && options.detach;
// Recursively run on children first (bottom up). We don't run
// view#_detach() on children as their references are cleared anyway.
for (var i = 0, l = this._children.length; i < l; i++) {
this._children[i].destroy({ skipEl: true });
}
// Detach this view from its parent and unless otherwise
// stated, from the DOM.
this._detach(options);
// Trigger a destroy event for custom Views to bind to.
this.trigger('destroy');
// Clear references.
this.el = this.module = this._id = this._globals = this._childHash = this._data = null;
},
/**
* Private Methods
*/
_toHTML: function(options) {
var template = this.template || templates[this.module];
var renderData = {};
// Don't template models that are flagged with render: false;
if (this.render === false) return;
// Check we have a template and that it has a 'render' method.
if (!template || !template.render) return; //util.error(this.module + ' has no template or the template has no render method');
// Create an array to store child html in.
renderData[SETTINGS.mustacheSlotArrayName] = [];
var child = this._children[i];
var html = child._toHTML(options);
// If no html was generated we don't want to add a slot
// to the parent's render data, so return here.
if (!html) return;
// Make the sub view html available to the parent model. So that when the
// parent model is rendered it can print the sub view html into the correct slot.
renderData[SETTINGS.mustacheSlotArrayName].push(util.extend({ module: html }, child._data));
renderData[SETTINGS.mustacheSlotVarPrefix + child._id] = html;
}
}
// Prepare the render data.
renderData['fm_classes'] = 'js-module';
renderData['fm_attrs'] = this._makeAttrs(options);
// Call render template.
return template.render(util.extend(renderData, this._data));
},
_makeAttrs: function(options) {
var attrs = {};
var embedData = options && options.embedData;
var forClient = options && options.forClient;
attrs[SETTINGS.moduleIdAttr] = this._id;
attrs[SETTINGS.moduleTypeAttr] = this.module;
if (embedData) {
attrs[SETTINGS.moduleDataAttr] = util.escape(JSON.stringify(this._data));
}
if (forClient && this.parent) {
return util.attributes(attrs);
},
_extractEmbeddedData: function(node) {
var data = node.getAttribute(SETTINGS.moduleDataAttr);
if (!data) return {};
data = JSON.parse(util.unescape(data));
node.removeAttribute(SETTINGS.moduleDataAttr);
return data;
},
_getDomChildren: function() {
if (debug) console.log('Searching for module elements...');
var nodes;
var domChildren = { all: [], byParent: {} };
if (!this.el) return domChildren;
nodes = this.el.getElementsByClassName(SETTINGS.slotClass);
// Loop over each module node found.
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
var child = {
el: node,
_id: node.getAttribute(SETTINGS.moduleIdAttr) || util.uniqueId('unknown'),
module: node.getAttribute(SETTINGS.moduleTypeAttr) || 'undefined',
parentId: node.getAttribute(SETTINGS.moduleParentAttr),
data: this._extractEmbeddedData(node)
};
domChildren.all.push(child);
if (child.parentId) {
domChildren.byParent[child.parentId] = domChildren.byParent[child.parentId] || [];
domChildren.byParent[child.parentId].push(child);
}
});
View['extend'] = function(module, options) {
FruitMachine.Views[module] = DefaultView.extend(options);
};
// We add the 'extend' static method to the FruitMachine base
// to add custom insteractions and logic to more complex modules.
// Redefining any of the View.prototype methods will overwrite them.
DefaultView.extend = util.inherits;
return FruitMachine;
}(this));
<MSG> - Updated comments and examples
<DFF> @@ -1,46 +1,77 @@
+
+/**
+ * FruitMachine
+ *
+ * Renders layouts/modules from a basic layout definition.
+ * If views require custom interactions devs can extend
+ * the basic functionality.
+ *
+ * Example:
+ *
+ * var definition = {
+ * module: 'orange',
+ * data: {
+ * title: 'A title',
+ * body: 'Some body copy'
+ * }
+ * };
+ *
+ * var view = new FruitMachine.View(definition);
+ *
+ * view
+ * .render()
+ * .inject(document.body)
+ * .setup();
+ *
+ * @version 0.1.0
+ * @copyright The Financial Times Limited [All Rights Reserved]
+ * @author Wilson Page <[email protected]>
+ */
+
+/*jslint browser:true, node:true*/
(function(root) {
'use strict';
- var FruitMachine = typeof exports === 'object' ? exports : root['FruitMachine'] = {};
+ var FruitMachine = typeof exports === 'object' ? exports : root.FruitMachine = {};
// Current Version
FruitMachine.VERSION = '0.0.1';
- /**
- * Turn on for debug messages.
- *
- * @constant
- * @type {Boolean|Number}
- */
- var debug = 0;
+ // Create local references to some native methods.
+ var slice = Array.prototype.slice;
/**
- * SETTINGS
+ * Settings
*/
- var SETTINGS = FruitMachine.SETTINGS = {
- breakpointDebounce: 50,
+ var SETTINGS = {
slotClass: 'js-module',
moduleIdAttr: 'data-module-id',
moduleTypeAttr: 'data-module-type',
moduleDataAttr: 'data-model-data',
moduleParentAttr: 'data-parent',
- mustacheSlotVarPrefix: 'module',
- mustacheSlotArrayName: 'modules'
+ mustacheSlotArrayName: 'children',
+ templates: undefined,
+ debug: 0
};
- var templates = {};
+ /**
+ * Sets a values onto the internal settings.
+ *
+ * @param {String|Object} key
+ * @param {*|null} val [description]
+ * @return void
+ */
- // User must define their templates before creating any Models or Views.
- var setTemplates = FruitMachine['templates'] = function(params) {
- util.extend(templates, params);
+ FruitMachine.set = function(key, val) {
+ if (typeof key === 'string') {
+ SETTINGS[key] = val;
+ } else {
+ util.extend(SETTINGS, val);
+ }
};
- // Create local references to some native methods.
- var slice = Array.prototype.slice;
- var splice = Array.prototype.splice;
- var forEach = Array.prototype.forEach;
-
- // An object that you can store your extended View classes in under module type.
+ // An object that stores your extended View
+ // classes in under module type.
FruitMachine.Views = {};
/**
@@ -51,11 +82,9 @@
attributes: function(attributes) {
var list = [];
-
for (var key in attributes) {
list.push(key + "='" + attributes[key] + "'");
}
-
return list.join(' ');
},
@@ -68,7 +97,6 @@
unescape: window.unescape,
extend: function(original) {
-
// Loop over every argument after the first.
slice.call(arguments, 1).forEach(function(source) {
for (var prop in source) {
@@ -79,42 +107,41 @@
return original;
},
-
inherits: function(protoProps, staticProps) {
var parent = this;
- var child;
+ var child;
- // The constructor function for the new subclass is either defined by you
- // (the "constructor" property in your `extend` definition), or defaulted
- // by us to simply call the parent's constructor.
- if (protoProps && protoProps.hasOwnProperty('constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ parent.apply(this, arguments); };
- }
+ // The constructor function for the new subclass is either defined by you
+ // (the "constructor" property in your `extend` definition), or defaulted
+ // by us to simply call the parent's constructor.
+ if (protoProps && protoProps.hasOwnProperty('constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ parent.apply(this, arguments); };
+ }
- // Inherit class (static) properties from parent.
- util.extend(child, parent);
+ // Inherit class (static) properties from parent.
+ util.extend(child, parent);
- // Set the prototype chain to inherit from `parent`, without calling
- // `parent`'s constructor function.
- util.ctor.prototype = parent.prototype;
- child.prototype = new util.ctor();
+ // Set the prototype chain to inherit from `parent`, without calling
+ // `parent`'s constructor function.
+ util.ctor.prototype = parent.prototype;
+ child.prototype = new util.ctor();
- // Add prototype properties (instance properties) to the subclass,
- // if supplied.
- if (protoProps) util.extend(child.prototype, protoProps);
+ // Add prototype properties (instance properties) to the subclass,
+ // if supplied.
+ if (protoProps) util.extend(child.prototype, protoProps);
- // Add static properties to the constructor function, if supplied.
- if (staticProps) util.extend(child, staticProps);
+ // Add static properties to the constructor function, if supplied.
+ if (staticProps) util.extend(child, staticProps);
- // Correctly set child's `prototype.constructor`.
- child.prototype.constructor = child;
+ // Correctly set child's `prototype.constructor`.
+ child.prototype.constructor = child;
- // Set a convenience property in case the parent's prototype is needed later.
- child.__super__ = parent.prototype;
+ // Set a convenience property in case the parent's prototype is needed later.
+ child.__super__ = parent.prototype;
- return child;
+ return child;
},
insertChild: function(child, parent, index) {
@@ -134,6 +161,10 @@
}
},
+ isArray: function(a) {
+ return (a instanceof Array);
+ },
+
/**
* Replaces the contents of the one node with contents
* of another.
@@ -166,24 +197,33 @@
return function(prefix) {
return (prefix || '') + (counter++) + '_' + Math.round(Math.random() * 100000);
};
- })()
+ })(),
+
+ /**
+ * Attempts to read and JSON parse
+ * any data found on the passed element's
+ * `data-module-data` attribute.
+ *
+ * If a data attribute is found, it is
+ * removed after it is read.
+ *
+ * @param {[type]} node [description]
+ * @return {[type]} [description]
+ */
+ extractEmbeddedData: function(el) {
+ var data = el.getAttribute(SETTINGS.moduleDataAttr);
+ if (!data) return {};
+ data = JSON.parse(util.unescape(data));
+ el.removeAttribute(SETTINGS.moduleDataAttr);
+ return data;
+ }
};
- // Backbone.Events
- // -----------------
-
- // Regular expression used to split event strings
- var eventSplitter = /\s+/;
-
- // A module that can be mixed in to *any object* in order to provide it with
- // custom events. You may bind with `on` or remove with `off` callback functions
- // to an event; trigger`-ing an event fires all callbacks in succession.
- //
- // var object = {};
- // _.extend(object, Backbone.Events);
- // object.on('expand', function(){ alert('expanded'); });
- // object.trigger('expand');
- //
+ /**
+ * Events
+ */
+
+ var splitter = /\s+/;
var Events = {
// Bind one or more space separated events, `events`, to a `callback`
@@ -192,19 +232,21 @@
var calls, event, node, tail, list;
if (!callback) return this;
- events = events.split(eventSplitter);
+ events = events.split(splitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
- while (event = events.shift()) {
+ event = events.shift();
+ while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {tail: tail, next: list ? list.next : node};
+ event = events.shift();
}
return this;
@@ -225,7 +267,7 @@
// Loop through the listed events and contexts, splicing them out of the
// linked list of callbacks if appropriate.
- events = events ? events.split(eventSplitter) : Object.keys(calls);
+ events = events ? events.split(splitter) : Object.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
@@ -252,7 +294,7 @@
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) return this;
all = calls.all;
- events = events.split(eventSplitter);
+ events = events.split(splitter);
rest = slice.call(arguments, 1);
// For each event, walk through the linked list of callbacks twice,
@@ -264,6 +306,7 @@
node.callback.apply(node.context || this, rest);
}
}
+
if (node = all) {
tail = node.tail;
args = [event].concat(rest);
@@ -281,26 +324,30 @@
* VIEW
*/
- var viewOptions = ['module', 'el', 'parent', '_globals'];
-
- var View = FruitMachine['View'] = function(options) {
- // Use a custom extended class if it exists for this module type
- // else use the default base view class.
+ var View = FruitMachine.View = function(options) {
var Constructor = FruitMachine.Views[options.module] || DefaultView;
return new Constructor(options);
};
+ /**
+ * Creates a new view instance.
+ *
+ * @constructor
+ * @param {Object} options
+ */
var DefaultView = function(options) {
- if (debug) console.log('Creating new view instance...');
var domChildren, i, l;
this._configure(options);
// Save a reference to this model in the globals.
this._globals.id[this._id] = this;
- // Don't look for module nodes in the view element if we have flagged not to.
- // When we initiate children we don't want to as the parent will have detected
- // all module nodes already when the master View was instantiated.
+ // Don't look for module nodes in the
+ // view element if we have flagged not to.
+ // When we initiate children we don't want
+ // to as the parent will have detected
+ // all module nodes already when the
+ // master View was instantiated.
if (!options.skipFindModuleNodes) {
this._globals.dom = this._getDomChildren();
}
@@ -308,20 +355,25 @@
// Find any DOM children with this parent
domChildren = this._globals.dom.byParent && this._globals.dom.byParent[this._id];
- // First we create View instances for each child found in the DOM.
+ // First we create View instances
+ // for each child found in the DOM.
//
- // This loop is for creating views from children which *have* DOM context.
+ // This loop is for creating views
+ // from children which *have* DOM context.
if (domChildren) {
for (i = 0, l = domChildren.length; i < l; i++) {
this._add(domChildren[i]);
}
}
- // ...then we create View instances for each child in the definition.
- // The internal _add method wont add a child if one already exists on
+ // ...then we create View instances
+ // for each child in the definition.
+ // The internal _add method wont add
+ // a child if one already exists on
// the parent with the same _id.
//
- // This loop is for creating fresh child views with *no* DOM context.
+ // This loop is for creating fresh
+ // child views with *no* DOM context.
if (options.children) {
for (i = 0, l = options.children.length; i < l; i++) {
this._add(options.children[i]);
@@ -334,6 +386,13 @@
util.extend(DefaultView.prototype, Events, {
+ /**
+ * Configure all options passed
+ * into the constructor.
+ *
+ * @param {Object} options
+ * @return void
+ */
_configure: function(options) {
this.parent = options.parent;
@@ -350,21 +409,64 @@
* Public Methods
*/
- // Fired when a View is instantiated, overwrite this yourself.
+ // Overwrite these yourself
initialize: function() {},
+ onSetup: function() {},
+ onTeardown: function() {},
+ onDestroy: function() {},
+
+ /**
+ * An internal api to add child views.
+ *
+ * Makes sure that the view doesn't
+ * already have this view as a child.
+ *
+ * @param {[type]} options [description]
+ */
_add: function(options) {
var hasChild = !!this._childHash[options._id || options.id];
if (hasChild) return;
+
options._globals = this._globals;
options.skipFindModuleNodes = true;
this.add(new View(options), { append: false });
},
+ /**
+ * Adds a child view.
+ *
+ * By default the view is appended,
+ * and if the View has an element,
+ * it is inserted into the parent
+ * element.
+ *
+ * Options:
+ * - `at` A specific index at which to add
+ * - `append` Staes if the View element is added to the parent
+ *
+ * @param {View|Object|Array} view
+ * @param {View} options
+ */
+
add: function(view, options) {
+ var children;
var at = options && options.at;
var append = options && options.append;
- if (debug) console.log('Adding view...');
+
+ // If the view passed in is not an instance
+ // of `DefaultView` then we need to turn the
+ // json into a View instance and re-add it.
+ // Array#concat() ensures we're always
+ // dealing with an Array.
+ if (!(view instanceof DefaultView)) {
+ children = [].concat(view);
+ for (var i = 0, l = children.length; i < l; i++) {
+ this.add(new View(children[i]));
+ }
+
+ return this;
+ }
// Merge the global variable stores.
util.extend(this._globals.id, view._globals.id);
@@ -382,21 +484,31 @@
this._childHash[view.module] = this._childHash[view.module] || [];
this._childHash[view.module].push(view);
+ // We append the child to the parent view if there is a view
+ // element and the users hasn't flagged `append` false.
if (append !== false && view.el) {
util.insertChild(view.el, this.el, at);
}
- // Return the newly created view.
+ // Allow chaining
return this;
},
- remove: function(view, options) {
-
- },
+ /**
+ * Renders a View instance.
+ *
+ * Options:
+ * - `asString` Simply returns html.
+ * - `embedData` Embeds view data as an html attribute
+ * - `forClient` Adds extra attributes for client interpretation
+ *
+ * @param {[type]} options [description]
+ * @return {[type]} [description]
+ */
render: function(options) {
var html = this._toHTML(options);
- var el, domChildren;
+ var el;
if (options && options.asString) return html;
@@ -405,54 +517,150 @@
// view element is not replaced, and we don't loose any delegate
// event listeners.
el = util.toNode(html);
- if (this.el) util.replaceContent(el, this.el);
- this.el = el;
+
+ if (this.el) {
+ util.replaceContent(el, this.el);
+ } else {
+ this.el = el;
+ }
// Update the View.els for each child View.
this.updateChildEls();
this.trigger('render');
- if (debug) console.log('View instance rendered.');
// Return this for chaining.
return this;
},
+ /**
+ * Fetches all child View elements,
+ * then allocates each element to
+ * a View instance by id.
+ *
+ * This is run when View#render() is
+ * called to assign newly rendered
+ * View elements to their View instances.
+ *
+ * @return {[type]} [description]
+ */
+
updateChildEls: function() {
var domChildren = this._getDomChildren().all;
+
for (var i = 0, l = domChildren.length; i < l; i++) {
var child = domChildren[i];
- this.id(child._id).el = child.el;
+ var match = this.id(child._id);
+ if (!match) continue;
+ match.el = child.el;
}
+
return this;
},
- get: function(key) {
- return key ? (this[key] || this._data[key]) : this._data;
- },
+ /**
+ * A single method for getting
+ * and setting view data.
+ *
+ * Example:
+ *
+ * // Getters
+ * var all = view.data();
+ * var one = view.data('myKey');
+ *
+ * // Setters
+ * view.data('myKey', 'my value');
+ * view.data({
+ * myKey: 'my value',
+ * anotherKey: 10
+ * });
+ *
+ * @param {String|Object|null} key
+ * @param {*} value
+ * @return {*}
+ */
- set: function(data, val) {
- if (typeof data === 'string') {
- this._data[data] = val;
- } else {
- util.extend(this._data, data);
+ data: function(key, value) {
+
+ // If no key and no value have
+ // been passed then return the
+ // entire data store.
+ if (!key && !value) {
+ return this._data;
}
- return this;
+ // If a string key has been
+ // passed, but no value
+ if (typeof key === 'string' && !value) {
+ return this._data[key];
+ }
+
+ // If the user has stated a key
+ // and a value. Set the value on
+ // the key.
+ if (key && value) {
+ this._data[key] = value;
+ this.trigger('datachange');
+ return this;
+ }
+
+ // If the key is an object literal
+ // then we extend the data store with it.
+ if ('object' === typeof key) {
+ util.extend(this._data, key);
+ this.trigger('datachange');
+ return this;
+ }
},
+ /**
+ * Returns a single immediate
+ * child View instance.
+ *
+ * Accepts a module type or view id.
+ *
+ * @param {[type]} query [description]
+ * @return {[type]} [description]
+ */
+
child: function(query) {
var result = this._childHash[query];
return result[0] || result;
},
+ /**
+ * Returns an array of children
+ * that match the query.
+ *
+ * @param {String} query
+ * @return {Array}
+ */
+
children: function(query) {
return this._childHash[query];
},
+ /**
+ * Returns a View instance by id or
+ * if no argument is given the id
+ * of the view.
+ *
+ * @param {String} id
+ * @return {View|String}
+ */
+
id: function(id) {
return id ? this._globals.id[id] : this._id;
},
+ /**
+ * Replaced the contents of the
+ * passed element with the view
+ * element.
+ *
+ * @param {Element} el
+ * @return {FruitMachine.View}
+ */
+
inject: function(el) {
if (!el) return this;
el.innerHTML = '';
@@ -460,25 +668,139 @@
return this;
},
+ /**
+ * Calls the `onSetup` event and
+ * triggers the `setup` event to
+ * allow you to do custom setup logic
+ * inside your custom views.
+ *
+ * @return {FruitMachine.View}
+ */
+
setup: function() {
- if (debug) console.log('Setting up view...');
- // Call 'setup' on all subviews first (bottom up recursion).
+ // Call 'setup' on all subviews
+ // first (bottom up recursion).
for (var i = 0, l = this._children.length; i < l; i++) {
this._children[i].setup();
}
- // We don't want to run setup on a module more than once, right?
- if (this.isSetup) return this;
+ // If this is already setup, call
+ // `teardown` first so that we don't
+ // duplicate event bindings and shizzle.
+ if (this.isSetup) this.teardown();
- // We trigger a 'setup' event that you can bind to
- // inside you custom Views to perform any setup logic.
+ // We trigger a `setup` event and
+ // call the `onSetup` method. You can
+ // listen to the `setup` event, or
+ // overwrite the `onSetup` method in
+ // your custom views to do setup logic.
this.trigger('setup');
-
- // Flag as setup
+ this.onSetup();
this.isSetup = true;
+
+ // For chaining
+ return this;
+ },
+
+ /**
+ * Teardown calls the `teardown`
+ * event on all children then on itself.
+ *
+ * Teardown allows custom views to listen to
+ * the event and unbind event listeners etc.
+ *
+ * Teardown should be used if the view
+ * itself is not going to be destroyed;
+ * just updated in some way.
+ *
+ * @return {View}
+ */
+
+ teardown: function() {
+ for (var i = 0, l = this._children.length; i < l; i++) {
+ this._children[i].teardown();
+ }
+
+ this.trigger('teardown');
+ this.onTeardown();
+ this.isSetup = false;
+
+ // For chaining
+ return this;
+ },
+
+ /**
+ * Destroys all children.
+ *
+ * @return {FruitMachine.View}
+ */
+
+ empty: function() {
+ while (this._children.length) {
+ this._children[0].destroy();
+ }
+
+ return this;
},
+ /**
+ * Recursively destroys all child views.
+ * This includes running `teardown`,
+ * detaching itself from the DOM and parent
+ * and unsetting any referenced.
+ *
+ * A `destroy` event is triggered and
+ * the `onDestroy` method is called.
+ * This allows you to bind to this event
+ * and destroy logic inside your custom views.
+ *
+ * @param {Object} options
+ * @return void
+ */
+
+ destroy: function(options) {
+
+ // Recursively run on children
+ // first (bottom up).
+ //
+ // We don't waste time removing
+ // the child elements as they will
+ // get removed when the parent
+ // element is removed.
+ while (this._children.length) {
+ this._children[0].destroy({ skipEl: true });
+ }
+
+ // Run teardown so custom
+ // views can bind logic to it
+ this.teardown(options);
+
+ // Detach this view from its
+ // parent and unless otherwise
+ // stated, from the DOM.
+ this._detach(options);
+
+ // Trigger a destroy event
+ // for custom Views to bind to.
+ this.trigger('destroy');
+ this.onDestroy();
+
+ // Set a flag to say this view
+ // has been destroyed. This is
+ // useful to check for after a
+ // slow ajax call that might come
+ // back after a view has been detroyed.
+ this.destroyed = true;
+
+ // Clear references
+ this.el = this.module = this._id = this._globals = this._childHash = this._data = null;
+ },
+
+ /**
+ * Private Methods
+ */
+
_detach: function(options) {
var i;
var skipEl = options && options.skipEl;
@@ -503,39 +825,29 @@
return this;
},
- destroy: function(options) {
- var detach = options && options.detach;
-
- // Recursively run on children first (bottom up). We don't run
- // view#_detach() on children as their references are cleared anyway.
- for (var i = 0, l = this._children.length; i < l; i++) {
- this._children[i].destroy({ skipEl: true });
- }
-
- // Detach this view from its parent and unless otherwise
- // stated, from the DOM.
- this._detach(options);
-
- // Trigger a destroy event for custom Views to bind to.
- this.trigger('destroy');
-
- // Clear references.
- this.el = this.module = this._id = this._globals = this._childHash = this._data = null;
- },
-
/**
- * Private Methods
+ * Recursively renders a view,
+ * and all child views, returning
+ * and html string.
+ *
+ * Options:
+ * - `embedData` Embeds view data as an html attribute
+ * - `forClient` Adds extra attributes for client interpretation
+ *
+ * @param {Object} options
+ * @return {String}
*/
_toHTML: function(options) {
- var template = this.template || templates[this.module];
+ var template = SETTINGS.templates(this.module);
var renderData = {};
- // Don't template models that are flagged with render: false;
+ // Don't template models that
+ // are flagged with render: false;
if (this.render === false) return;
- // Check we have a template and that it has a 'render' method.
- if (!template || !template.render) return; //util.error(this.module + ' has no template or the template has no render method');
+ // Check we have a template
+ if (!template) return;
// Create an array to store child html in.
renderData[SETTINGS.mustacheSlotArrayName] = [];
@@ -545,27 +857,40 @@
var child = this._children[i];
var html = child._toHTML(options);
- // If no html was generated we don't want to add a slot
- // to the parent's render data, so return here.
+ // If no html was generated we
+ // don't want to add a slot to the
+ // parent's render data, so return here.
if (!html) return;
- // Make the sub view html available to the parent model. So that when the
- // parent model is rendered it can print the sub view html into the correct slot.
- renderData[SETTINGS.mustacheSlotArrayName].push(util.extend({ module: html }, child._data));
- renderData[SETTINGS.mustacheSlotVarPrefix + child._id] = html;
+ // Make the sub view html available
+ // to the parent model. So that when the
+ // parent model is rendered it can print
+ // the sub view html into the correct slot.
+ renderData[SETTINGS.mustacheSlotArrayName].push(util.extend({ child: html }, child.data()));
+ renderData[child._id] = html;
}
}
// Prepare the render data.
- renderData['fm_classes'] = 'js-module';
- renderData['fm_attrs'] = this._makeAttrs(options);
+ renderData.fm_classes = SETTINGS.slotClass;
+ renderData.fm_attrs = this._htmlAttrs(options);
// Call render template.
- return template.render(util.extend(renderData, this._data));
+ return template(util.extend(renderData, this.data()));
},
+ /**
+ * Creates an html attribute string.
+ *
+ * Options:
+ * - `embedData` Embeds view.data() as an html attribute
+ * - `forClient` Adds extra attributes for client interpretation
+ *
+ * @param {Object} options
+ * @return {String}
+ */
- _makeAttrs: function(options) {
+ _htmlAttrs: function(options) {
var attrs = {};
var embedData = options && options.embedData;
var forClient = options && options.forClient;
@@ -574,8 +899,10 @@
attrs[SETTINGS.moduleIdAttr] = this._id;
attrs[SETTINGS.moduleTypeAttr] = this.module;
+ // If embedded data has been requested
+ // stringify and escape the
if (embedData) {
- attrs[SETTINGS.moduleDataAttr] = util.escape(JSON.stringify(this._data));
+ attrs[SETTINGS.moduleDataAttr] = util.escape(JSON.stringify(this.data()));
}
if (forClient && this.parent) {
@@ -585,35 +912,34 @@
return util.attributes(attrs);
},
- _extractEmbeddedData: function(node) {
- var data = node.getAttribute(SETTINGS.moduleDataAttr);
- if (!data) return {};
- data = JSON.parse(util.unescape(data));
- node.removeAttribute(SETTINGS.moduleDataAttr);
- return data;
- },
-
+ /**
+ * Returns all child module elements.
+ *
+ * @return {Object} {all: {Array}, byParent: {Object}}
+ */
_getDomChildren: function() {
- if (debug) console.log('Searching for module elements...');
- var nodes;
+ var els;
var domChildren = { all: [], byParent: {} };
if (!this.el) return domChildren;
- nodes = this.el.getElementsByClassName(SETTINGS.slotClass);
+ els = this.el.getElementsByClassName(SETTINGS.slotClass);
// Loop over each module node found.
- for (var i = 0, l = nodes.length; i < l; i++) {
- var node = nodes[i];
+ for (var i = 0, l = els.length; i < l; i++) {
+ var el = els[i];
var child = {
- el: node,
- _id: node.getAttribute(SETTINGS.moduleIdAttr) || util.uniqueId('unknown'),
- module: node.getAttribute(SETTINGS.moduleTypeAttr) || 'undefined',
- parentId: node.getAttribute(SETTINGS.moduleParentAttr),
- data: this._extractEmbeddedData(node)
+ el: el,
+ _id: el.getAttribute(SETTINGS.moduleIdAttr) || util.uniqueId('unknown'),
+ module: el.getAttribute(SETTINGS.moduleTypeAttr) || 'undefined',
+ parentId: el.getAttribute(SETTINGS.moduleParentAttr),
+ data: util.extractEmbeddedData(el)
};
domChildren.all.push(child);
+ // If a parent-id was found on the
+ // element, store a second reference
+ // with the parent id as the key.
if (child.parentId) {
domChildren.byParent[child.parentId] = domChildren.byParent[child.parentId] || [];
domChildren.byParent[child.parentId].push(child);
@@ -624,8 +950,8 @@
}
});
- View['extend'] = function(module, options) {
- FruitMachine.Views[module] = DefaultView.extend(options);
+ View.extend = function(module, protoProps, staticProps) {
+ FruitMachine.Views[module] = DefaultView.extend(protoProps, staticProps);
};
// We add the 'extend' static method to the FruitMachine base
@@ -633,6 +959,4 @@
// to add custom insteractions and logic to more complex modules.
// Redefining any of the View.prototype methods will overwrite them.
DefaultView.extend = util.inherits;
-
- return FruitMachine;
}(this));
\ No newline at end of file
| 496 | - Updated comments and examples | 172 | .js | js | mit | ftlabs/fruitmachine |
10066752 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066753 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066754 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066755 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066756 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066757 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066758 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066759 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066760 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066761 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066762 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066763 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066764 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066765 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066766 | <NME> CSharp-Mode.xshd
<BEF> <?xml version="1.0"?>
<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name="Comment" foreground="Green" exampleText="// comment" />
<Color name="String" foreground="Blue" exampleText="string text = "Hello, World!""/>
<Color name="StringInterpolation" foreground="Black" exampleText="string text = $"Hello, {name}!""/>
<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
<Color name="Punctuation" exampleText="a(b.c);" />
<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
<Keywords fontWeight="bold" foreground="Red">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight="bold" foreground="#E0E000">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet>
<Span color="Preprocessor">
<Begin>\#</Begin>
<RuleSet name="PreprocessorSet">
<Span> <!-- preprocessor directives that allows comments -->
<Begin fontWeight="bold">
(define|undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span> <!-- preprocessor directives that don't allow comments -->
<Begin fontWeight="bold">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>
<Span color="Comment">
<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
<RuleSet>
<Import ruleSet="XmlDoc/DocCommentSet"/>
<Import ruleSet="CommentMarkerSet"/>
</RuleSet>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet">
<Begin>//</Begin>
</Span>
<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="Char">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
</RuleSet>
</Span>
<Span color="String" multiline="true">
<Begin>@"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin='""' end=""/>
</RuleSet>
</Span>
<Span color="String">
<Begin>\$"</Begin>
<End>"</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin="\\" end="."/>
<Span begin="\{\{" end=""/>
<!-- string interpolation -->
<Span begin="{" end="}" color="StringInterpolation" ruleSet=""/>
</RuleSet>
</Span>
<!-- don't highlight "@int" as keyword -->
<Rule>
@[\w\d_]+
</Rule>
<Keywords color="ThisOrBaseReference">
<Word>this</Word>
<Word>base</Word>
</Keywords>
<Keywords color="TypeKeywords">
<Word>as</Word>
<Word>is</Word>
<Word>new</Word>
<Word>sizeof</Word>
<Word>typeof</Word>
<Word>stackalloc</Word>
</Keywords>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>else</Word>
<Word>if</Word>
<Word>switch</Word>
<Word>case</Word>
<Word>default</Word>
<Word>do</Word>
<Word>for</Word>
<Word>foreach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>lock</Word>
</Keywords>
<Keywords color="GotoKeywords">
<Word>break</Word>
<Word>continue</Word>
<Word>goto</Word>
<Word>return</Word>
</Keywords>
<Keywords color="ContextKeywords">
<Word>yield</Word>
<Word>partial</Word>
<Word>global</Word>
<Word>where</Word>
<Word>select</Word>
<Word>group</Word>
<Word>by</Word>
<Word>into</Word>
<Word>from</Word>
<Word>ascending</Word>
<Word>descending</Word>
<Word>orderby</Word>
<Word>let</Word>
<Word>join</Word>
<Word>on</Word>
<Word>equals</Word>
<Word>var</Word>
<Word>dynamic</Word>
<Word>await</Word>
</Keywords>
<Keywords color="ExceptionKeywords">
<Word>try</Word>
<Word>throw</Word>
<Word>catch</Word>
<Word>finally</Word>
</Keywords>
<Keywords color="CheckedKeyword">
<Word>checked</Word>
<Word>unchecked</Word>
</Keywords>
<Keywords color="UnsafeKeywords">
<Word>fixed</Word>
<Word>unsafe</Word>
</Keywords>
<Keywords color="ValueTypeKeywords">
<Word>bool</Word>
<Word>byte</Word>
<Word>char</Word>
<Word>decimal</Word>
<Word>double</Word>
<Word>enum</Word>
<Word>float</Word>
<Word>int</Word>
<Word>long</Word>
<Word>sbyte</Word>
<Word>short</Word>
<Word>struct</Word>
<Word>uint</Word>
<Word>ushort</Word>
<Word>ulong</Word>
</Keywords>
<Keywords color="ReferenceTypeKeywords">
<Word>class</Word>
<Word>interface</Word>
<Word>delegate</Word>
<Word>object</Word>
<Word>string</Word>
<Word>void</Word>
</Keywords>
<Keywords color="OperatorKeywords">
<Word>explicit</Word>
<Word>implicit</Word>
<Word>operator</Word>
</Keywords>
<Keywords color="ParameterModifiers">
<Word>params</Word>
<Word>ref</Word>
<Word>out</Word>
</Keywords>
<Keywords color="Modifiers">
<Word>abstract</Word>
<Word>const</Word>
<Word>event</Word>
<Word>extern</Word>
<Word>override</Word>
<Word>readonly</Word>
<Word>sealed</Word>
<Word>static</Word>
<Word>virtual</Word>
<Word>volatile</Word>
<Word>async</Word>
</Keywords>
<Keywords color="Visibility">
<Word>public</Word>
<Word>protected</Word>
<Word>private</Word>
<Word>internal</Word>
</Keywords>
<Keywords color="NamespaceKeywords">
<Word>namespace</Word>
<Word>using</Word>
</Keywords>
<Keywords color="GetSetAddRemove">
<Word>get</Word>
<Word>set</Word>
<Word>add</Word>
<Word>remove</Word>
</Keywords>
<Keywords color="NullOrValueKeywords">
<Word>null</Word>
<Word>value</Word>
</Keywords>
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
[\d\w_]+ # an identifier
(?=\s*\() # followed by (
</Rule>
<!-- Digits -->
<Rule color="NumberLiteral">
\b0[xX][0-9a-fA-F]+ # hex number
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
([eE][+-]?[0-9]+)? # optional exponent
</Rule>
<Rule color="Punctuation">
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
</SyntaxDefinition>
<MSG> C# syntax highlighting: added support for the nameof keyword.
(https://github.com/icsharpcode/AvalonEdit/pull/94)
<DFF> @@ -27,7 +27,8 @@
<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
-
+ <Color name="SemanticKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (args == null) throw new ArgumentNullException(nameof(args));" />
+
<Property name="DocCommentMarker" value="///" />
<RuleSet name="CommentMarkerSet">
@@ -280,7 +281,11 @@
<Word>null</Word>
<Word>value</Word>
</Keywords>
-
+
+ <Keywords color="SemanticKeywords">
+ <Word>nameof</Word>
+ </Keywords>
+
<!-- Mark previous rule-->
<Rule color="MethodCall">
\b
@@ -302,4 +307,4 @@
[?,.;()\[\]{}+\-/%*<>^+~!|&]+
</Rule>
</RuleSet>
-</SyntaxDefinition>
+</SyntaxDefinition>
\ No newline at end of file
| 8 | C# syntax highlighting: added support for the nameof keyword. | 3 | .xshd | xshd | mit | AvaloniaUI/AvaloniaEdit |
10066767 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066768 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066769 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066770 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066771 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066772 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066773 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066774 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066775 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066776 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066777 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066778 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066779 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066780 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066781 | <NME> TextAreaDefaultInputHandlers.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.Windows.Input;
using AvaloniaEdit.Document;
using Avalonia.Input;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Contains the predefined input handlers.
/// </summary>
public class TextAreaDefaultInputHandler : TextAreaInputHandler
{
/// <summary>
/// Gets the caret navigation input handler.
/// </summary>
public TextAreaInputHandler CaretNavigation { get; }
/// <summary>
/// Gets the editing input handler.
/// </summary>
public TextAreaInputHandler Editing { get; }
/// <summary>
/// Gets the mouse selection input handler.
/// </summary>
public ITextAreaInputHandler MouseSelection { get; }
/// <summary>
/// Creates a new TextAreaDefaultInputHandler instance.
/// </summary>
public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
{
NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
AddBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo);
AddBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo);
}
private void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
}
#region Undo / Redo
private UndoStack GetUndoStack()
{
var document = TextArea.Document;
return document?.UndoStack;
}
private void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanUndo)
{
undoStack.Undo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanUndo;
}
}
private void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
if (undoStack.CanRedo)
{
undoStack.Redo();
TextArea.Caret.BringCaretToView();
}
e.Handled = true;
}
}
private void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
{
var undoStack = GetUndoStack();
if (undoStack != null)
{
e.Handled = true;
e.CanExecute = undoStack.CanRedo;
}
}
#endregion
}
}
<MSG> Merge pull request #161 from AvaloniaUI/fix-macos-keybindings
Fix osx-specific key shortcuts
<DFF> @@ -63,7 +63,12 @@ namespace AvaloniaEdit.Editing
internal static KeyBinding CreateKeyBinding(ICommand command, KeyModifiers modifiers, Key key)
{
- return new KeyBinding { Command = command, Gesture = new KeyGesture(key, modifiers) };
+ return CreateKeyBinding(command, new KeyGesture(key, modifiers));
+ }
+
+ internal static KeyBinding CreateKeyBinding(ICommand command, KeyGesture gesture)
+ {
+ return new KeyBinding { Command = command, Gesture = gesture };
}
#region Undo / Redo
| 6 | Merge pull request #161 from AvaloniaUI/fix-macos-keybindings | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066782 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066783 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066784 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066785 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066786 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066787 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066788 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066789 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066790 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066791 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066792 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066793 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066794 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066795 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066796 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
return panel;
}
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// Removes the SearchPanel from the TextArea.
/// </summary>
public void Uninstall()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
/// </summary>
public void Close()
{
_textArea.RemoveChild(this);
_messageView.IsOpen = false;
_textArea.TextView.BackgroundRenderers.Remove(_renderer);
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> correctly attach the searchpanel to the logical tree.
<DFF> @@ -217,6 +217,8 @@ namespace AvaloniaEdit.Search
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
+ ((ISetLogicalParent)panel).SetParent(textArea);
+
return panel;
}
| 2 | correctly attach the searchpanel to the logical tree. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066797 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066798 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066799 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066800 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066801 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066802 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066803 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066804 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066805 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066806 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066807 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066808 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066809 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066810 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066811 | <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.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
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;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
_textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
private int _currentTheme = (int)ThemeName.DarkPlus;
public MainWindow()
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_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.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_changeThemeButton = this.FindControl<Button>("changeThemeBtn");
_changeThemeButton.Click += ChangeThemeButton_Click;
_textEditor.TextArea.TextView.ElementGenerators.Add(_generator);
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
//TODO: delete elements using back key
_generator.controls.Clear();
_textEditor.TextArea.TextView.Redraw();
}
private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
{
if (!char.IsLetterOrDigit(e.Text[0]))
{
// Whenever a non-letter is typed while the completion window is open,
// insert the currently selected element.
_completionWindow.CompletionList.RequestInsertion(e);
}
}
_insightWindow?.Hide();
// Do not set e.Handled=true.
// We still want to insert the character that was typed.
}
private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e)
{
if (e.Text == ".")
{
_completionWindow = new CompletionWindow(_textEditor.TextArea);
_completionWindow.Closed += (o, args) => _completionWindow = null;
var data = _completionWindow.CompletionList.CompletionData;
data.Add(new MyCompletionData("Item1"));
data.Add(new MyCompletionData("Item2"));
data.Add(new MyCompletionData("Item3"));
data.Add(new MyCompletionData("Item4"));
data.Add(new MyCompletionData("Item5"));
data.Add(new MyCompletionData("Item6"));
data.Add(new MyCompletionData("Item7"));
data.Add(new MyCompletionData("Item8"));
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> correct demo setup.
<DFF> @@ -13,7 +13,6 @@ using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
-using AvaloniaEdit.Search;
namespace AvaloniaEdit.Demo
{
@@ -33,13 +32,7 @@ namespace AvaloniaEdit.Demo
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
- _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
- var lineNumberMargin = new LineNumberMargin { Margin = new Thickness(0, 0, 10, 0) };
- TextBlock.SetForeground(lineNumberMargin, Brushes.Gray);
- _textEditor.TextArea.LeftMargins.Add(lineNumberMargin);
- _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy( );
- SearchPanel.Install(_textEditor);
}
private void InitializeComponent()
| 0 | correct demo setup. | 7 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10066812 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
* - `Model` A model constructor to use (must have `.toJSON()`)
*
* @param {Object} options
*/
module.exports = function(options) {
/**
* Shortcut method for
* creating lazy views.
*
* @param {Object} options
* @return {Module}
*/
function fm(options) {
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
}
fm.create = module.exports;
fm.Model = options.Model;
fm.Events = events;
fm.Module = mod(fm);
fm.define = define(fm);
fm.util = utils;
fm.modules = {};
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
return store.templates[module];
};
var View = FruitMachine.View = function(options) {
options = mixin({}, options);
if (options.module) return create(options);
*
* Options:
*
* - `bubble` States whether the event
* should bubble through parent views.
*
* @param {String} key
* @return {View}
* @api public
*/
trigger: function(key, args, options) {
options = options || {};
// Allows options to be
// the second or third arg
if (!util.isArray(args)) {
options = args || {};
args = [];
}
// Trigger event
Events.trigger.apply(this, [key].concat(args));
// Trigger the same event on the parent view
if (options.bubble && this.parent) this.parent.trigger(key, args, options);
// Allow chaining
return this;
<MSG> Implement bubbling events (closes #3)
<DFF> @@ -273,6 +273,10 @@
return store.templates[module];
};
+ var stopPropagation = function() {
+ this.propagate = false;
+ };
+
var View = FruitMachine.View = function(options) {
options = mixin({}, options);
if (options.module) return create(options);
@@ -313,7 +317,7 @@
*
* Options:
*
- * - `bubble` States whether the event
+ * - `propagate` States whether the event
* should bubble through parent views.
*
* @param {String} key
@@ -322,21 +326,31 @@
* @return {View}
* @api public
*/
- trigger: function(key, args, options) {
- options = options || {};
+ trigger: function(key, args, event) {
+ var propagate;
- // Allows options to be
- // the second or third arg
+ // event can be passed as
+ // the second or third argument
if (!util.isArray(args)) {
- options = args || {};
+ event = args;
args = [];
}
+ // Use the event object passed
+ // in, or make a fresh one
+ event = event || { stopPropagation: stopPropagation };
+
// Trigger event
- Events.trigger.apply(this, [key].concat(args));
+ Events.trigger.apply(this, [key, event].concat(args));
+
+ // Propagate by default
+ propagate = (event.propagate === false)
+ ? false
+ : true;
- // Trigger the same event on the parent view
- if (options.bubble && this.parent) this.parent.trigger(key, args, options);
+ // Trigger the same
+ // event on the parent view
+ if (propagate && this.parent) this.parent.trigger(key, args, event);
// Allow chaining
return this;
| 23 | Implement bubbling events (closes #3) | 9 | .js | js | mit | ftlabs/fruitmachine |
10066813 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066814 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066815 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066816 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066817 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066818 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066819 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066820 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066821 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066822 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066823 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066824 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066825 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066826 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066827 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update to avalonia beta-1
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4554-alpha" />
+ <PackageReference Include="Avalonia" Version="0.6.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update to avalonia beta-1 | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10066828 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped).
Here's an example of what you can do with LoadJS:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle and execute code when it loads
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [loadjs.js](dist/loadjs.js)
* [loadjs.min.js](dist/loadjs.min.js)
You can also use it as a CJS or AMD module:
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
.catch(function(pathsNotFound) { /* at least one didn't load */ });
```
1. Check if bundle has already been defined
```javascript
if (!loadjs.isDefined('foobar')) {
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
}
```
1. Fetch files in parallel and load them in series
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() { /* foo.js and bar.js loaded in series */ },
async: false
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> updated readme
<DFF> @@ -27,8 +27,8 @@ loadjs.ready('foobar', {
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
- * [loadjs.js](dist/loadjs.js)
- * [loadjs.min.js](dist/loadjs.min.js)
+ * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
+ * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js)
You can also use it as a CJS or AMD module:
| 2 | updated readme | 2 | .md | md | mit | muicss/loadjs |
10066829 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped).
Here's an example of what you can do with LoadJS:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle and execute code when it loads
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [loadjs.js](dist/loadjs.js)
* [loadjs.min.js](dist/loadjs.min.js)
You can also use it as a CJS or AMD module:
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
.catch(function(pathsNotFound) { /* at least one didn't load */ });
```
1. Check if bundle has already been defined
```javascript
if (!loadjs.isDefined('foobar')) {
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
}
```
1. Fetch files in parallel and load them in series
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() { /* foo.js and bar.js loaded in series */ },
async: false
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> updated readme
<DFF> @@ -27,8 +27,8 @@ loadjs.ready('foobar', {
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
- * [loadjs.js](dist/loadjs.js)
- * [loadjs.min.js](dist/loadjs.min.js)
+ * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
+ * [loadjs.min.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js)
You can also use it as a CJS or AMD module:
| 2 | updated readme | 2 | .md | md | mit | muicss/loadjs |
10066830 | <NME> helpers.js
<BEF> buster.testCase('fruitmachine#helpers()', {
setUp: function() {
var helper = this.helper = function(view) {
view.on('initialize', helper.initialize);
view.on('setup', helper.setup);
view.on('teardown', helper.teardown);
view.on('destroy', helper.destroy);
};
helper.initialize = function() {};
helper.setup = function() {};
helper.teardown = function() {};
helper.destroy = function() {};
this.spys = {
initialize: this.spy(this.helper, 'initialize'),
setup: this.spy(this.helper, 'setup'),
teardown: this.spy(this.helper, 'teardown'),
var view = fruitmachine({
};
},
"helper `initialize` should have been called": function() {
var view = fruitmachine({
module: 'apple',
helpers: [this.helper]
});
assert.isTrue(this.spys.initialize.called);
},
"helper `setup` should have been called": function() {
module: 'apple',
helpers: [testHelper]
});
expect(testHelper.setup).toHaveBeenCalledTimes(0);
view
.render()
.inject(sandbox)
.setup();
expect(testHelper.setup).toHaveBeenCalledTimes(1);
});
test("helper `teardown` and `destroy` should have been called", function() {
var view = fruitmachine({
module: 'apple',
helpers: [testHelper]
});
view
.render()
.inject(sandbox)
.setup()
.teardown()
.destroy();
expect(testHelper.teardown).toHaveBeenCalled();
expect(testHelper.destroy).toHaveBeenCalled();
});
});
<MSG> Add tests for befoer initialize
<DFF> @@ -1,18 +1,21 @@
buster.testCase('fruitmachine#helpers()', {
setUp: function() {
var helper = this.helper = function(view) {
+ view.on('before initialize', helper.beforeInitialize);
view.on('initialize', helper.initialize);
view.on('setup', helper.setup);
view.on('teardown', helper.teardown);
view.on('destroy', helper.destroy);
};
+ helper.beforeInitialize = function() {};
helper.initialize = function() {};
helper.setup = function() {};
helper.teardown = function() {};
helper.destroy = function() {};
this.spys = {
+ beforeInitialize: this.spy(this.helper, 'beforeInitialize'),
initialize: this.spy(this.helper, 'initialize'),
setup: this.spy(this.helper, 'setup'),
teardown: this.spy(this.helper, 'teardown'),
@@ -20,13 +23,15 @@ buster.testCase('fruitmachine#helpers()', {
};
},
- "helper `initialize` should have been called": function() {
+ "helpers `before initialize` and `initialize` should have been called, in that order": function() {
var view = fruitmachine({
module: 'apple',
helpers: [this.helper]
});
assert.isTrue(this.spys.initialize.called);
+ assert.isTrue(this.spys.beforeInitialize.called);
+ assert.callOrder(this.spys.beforeInitialize, this.spys.initialize);
},
"helper `setup` should have been called": function() {
| 6 | Add tests for befoer initialize | 1 | .js | js | mit | ftlabs/fruitmachine |
10066831 | <NME> view.js
<BEF> ADDFILE
<MSG> Instantiation tests
<DFF> @@ -0,0 +1,35 @@
+
+buster.testCase('View', {
+ "Should add any children passed into the constructor": function() {
+ var children = [
+ {
+ module: 'pear'
+ },
+ {
+ module: 'orange'
+ }
+ ];
+
+ var view = new FruitMachine.View({
+ module: 'apple',
+ children: children
+ });
+
+ assert.equals(view.children().length, 2);
+ },
+
+ "Should create a model": function() {
+ var view = new FruitMachine.View({ module: 'apple' });
+ assert.isTrue(view.model instanceof FruitMachine.Model);
+ },
+
+ "Should setup an event listener to purge html cache when model changes": function() {
+ var spy = this.spy(FruitMachine.View.prototype, 'purgeHtmlCache');
+ var view = new FruitMachine.View({ module: 'orange' });
+
+ view.model.set('foo', 'bar');
+
+ assert.called(spy);
+ spy.restore();
+ }
+});
\ No newline at end of file
| 35 | Instantiation tests | 0 | .js | js | mit | ftlabs/fruitmachine |
10066832 | <NME> fruitmachine_test.js
<BEF> ADDFILE
<MSG> - First commit
<DFF> @@ -0,0 +1,35 @@
+/*global require:true */
+var fruitmachine = require('../lib/fruitmachine.js');
+
+/*
+ ======== A Handy Little Nodeunit Reference ========
+ https://github.com/caolan/nodeunit
+
+ Test methods:
+ test.expect(numAssertions)
+ test.done()
+ Test assertions:
+ test.ok(value, [message])
+ test.equal(actual, expected, [message])
+ test.notEqual(actual, expected, [message])
+ test.deepEqual(actual, expected, [message])
+ test.notDeepEqual(actual, expected, [message])
+ test.strictEqual(actual, expected, [message])
+ test.notStrictEqual(actual, expected, [message])
+ test.throws(block, [error], [message])
+ test.doesNotThrow(block, [error], [message])
+ test.ifError(value)
+*/
+
+exports['awesome'] = {
+ setUp: function(done) {
+ // setup here
+ done();
+ },
+ 'no args': function(test) {
+ test.expect(1);
+ // tests here
+ test.equal(fruitmachine.awesome(), 'awesome', 'should be awesome.');
+ test.done();
+ }
+};
| 35 | - First commit | 0 | .js | js | mit | ftlabs/fruitmachine |
10066833 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('should call fail callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
loadjs('assets/file2.js', 'bundle6');
loadjs
.ready('bundle5', function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
})
.ready('bundle6', function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
});
});
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
loadjs.ready(['bundle7', 'bundle8'], function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
it('should support async false', function(done) {
this.timeout(5000);
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
loadjs.ready(['bundle9', 'bundle10'],
function() {
throw "Executed success callback";
},
function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
done();
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin1', function() {
done();
});
// execute done
done();
} else {
// reset register
pathsLoaded = {};
// run test again
loadjs.done('plugin2');
// add handler
loadjs.ready('plugin2', function() {
done();
});
});
});
it('should support multiple tries', function(done) {
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle1', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
}, 1000);
});
// Un-'x' this for testing ad blocked scripts.
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle2', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
// use 1 second delay
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
}, 1000);
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
}
});
xit('it should report ad blocked scripts as missing', function(done) {
var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js';
loadjs([blockedScript, 'assets/file1.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
done();
});
});
});
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> Modifies API, adds support for async: false, bumps version number
<DFF> @@ -18,46 +18,52 @@ describe('LoadJS tests', function() {
it('should call success callback on valid path', function(done) {
- loadjs(['assets/file1.js'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- done();
+ loadjs(['assets/file1.js'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ done();
+ }
});
});
it('should call fail callback on invalid path', function(done) {
- loadjs(['assets/file-doesntexist.js'],
- function() {
- throw "Executed success callback";
- },
- function(pathsNotFound) {
- assert.equal(pathsNotFound.length, 1);
- assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
- done();
- });
+ loadjs(['assets/file-doesntexist.js'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ });
});
it('should call success callback on two valid paths', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs(['assets/file1.js', 'assets/file2.js'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
it('should call fail callback on one invalid path', function(done) {
- loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
- function() {
- throw "Executed success callback";
- },
- function(pathsNotFound) {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsNotFound.length, 1);
- assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
- done();
- });
+ loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(pathsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ });
});
@@ -75,10 +81,12 @@ describe('LoadJS tests', function() {
it('should create a bundle id and a callback inline', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
@@ -93,13 +101,16 @@ describe('LoadJS tests', function() {
loadjs('assets/file2.js', 'bundle6');
loadjs
- .ready('bundle5', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- bothDone();
- })
- .ready('bundle6', function() {
- assert.equal(pathsLoaded['file2.js'], true);
- bothDone();
+ .ready('bundle5', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ bothDone();
+ }})
+ .ready('bundle6', {
+ success: function() {
+ assert.equal(pathsLoaded['file2.js'], true);
+ bothDone();
+ }
});
});
@@ -108,10 +119,12 @@ describe('LoadJS tests', function() {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
- loadjs.ready(['bundle7', 'bundle8'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready(['bundle7', 'bundle8'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
@@ -120,23 +133,26 @@ describe('LoadJS tests', function() {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
- loadjs.ready(['bundle9', 'bundle10'],
- function() {
- throw "Executed success callback";
- },
- function(depsNotFound) {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(depsNotFound.length, 1);
- assert.equal(depsNotFound[0], 'bundle10');
- done();
- });
+ loadjs.ready(['bundle9', 'bundle10'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(depsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(depsNotFound.length, 1);
+ assert.equal(depsNotFound[0], 'bundle10');
+ done();
+ }
+ });
});
it('should execute callbacks on .done()', function(done) {
// add handler
- loadjs.ready('plugin1', function() {
- done();
+ loadjs.ready('plugin1', {
+ success: function() {
+ done();
+ }
});
// execute done
@@ -149,8 +165,10 @@ describe('LoadJS tests', function() {
loadjs.done('plugin2');
// add handler
- loadjs.ready('plugin2', function() {
- done();
+ loadjs.ready('plugin2', {
+ success: function() {
+ done();
+ }
});
});
@@ -161,10 +179,12 @@ describe('LoadJS tests', function() {
// use 1 second delay to let files load
setTimeout(function() {
- loadjs.ready('bundle1', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready('bundle1', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
}, 1000);
});
@@ -172,10 +192,12 @@ describe('LoadJS tests', function() {
it('should allow bundle callbacks before definitions', function(done) {
// define callback
- loadjs.ready('bundle2', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready('bundle2', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
// use 1 second delay
@@ -184,6 +206,47 @@ describe('LoadJS tests', function() {
}, 1000);
});
+
+ it('should support async false', function(done) {
+ var numCompleted = 0,
+ numTests = 20,
+ paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
+
+ // run tests sequentially
+ var testFn = function(paths) {
+ loadjs(paths, {
+ success: function() {
+ var f1 = paths[0].replace('assets/', '');
+ var f2 = paths[1].replace('assets/', '');
+
+ // check load order
+ assert.isTrue(pathsLoaded[f1]);
+ assert.isFalse(pathsLoaded[f2]);
+
+ // increment tests
+ numCompleted += 1;
+
+ if (numCompleted === numTests) {
+ // exit
+ done();
+ } else {
+ // reset register
+ pathsLoaded = {};
+
+ // run test again
+ paths.reverse();
+ testFn(paths);
+ }
+ },
+ async: false
+ });
+ }
+
+ // run tests
+ testFn(paths);
+ });
+
+
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
@@ -192,15 +255,16 @@ describe('LoadJS tests', function() {
xit('it should report ad blocked scripts as missing', function(done) {
var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js';
- loadjs([blockedScript, 'assets/file1.js'],
- function() {
+ loadjs([blockedScript, 'assets/file1.js'], {
+ success: function() {
throw "Executed success callback";
},
- function(pathsNotFound) {
+ fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
done();
- });
+ }
+ });
});
});
| 131 | Modifies API, adds support for async: false, bumps version number | 67 | .js | js | mit | muicss/loadjs |
10066834 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('should call fail callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
loadjs('assets/file2.js', 'bundle6');
loadjs
.ready('bundle5', function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
})
.ready('bundle6', function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
});
});
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
loadjs.ready(['bundle7', 'bundle8'], function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
});
it('should support async false', function(done) {
this.timeout(5000);
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
loadjs.ready(['bundle9', 'bundle10'],
function() {
throw "Executed success callback";
},
function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
done();
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin1', function() {
done();
});
// execute done
done();
} else {
// reset register
pathsLoaded = {};
// run test again
loadjs.done('plugin2');
// add handler
loadjs.ready('plugin2', function() {
done();
});
});
});
it('should support multiple tries', function(done) {
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle1', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
}, 1000);
});
// Un-'x' this for testing ad blocked scripts.
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle2', function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
});
// use 1 second delay
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
}, 1000);
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
}
});
xit('it should report ad blocked scripts as missing', function(done) {
var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js';
loadjs([blockedScript, 'assets/file1.js'],
function() {
throw "Executed success callback";
},
function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
done();
});
});
});
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> Modifies API, adds support for async: false, bumps version number
<DFF> @@ -18,46 +18,52 @@ describe('LoadJS tests', function() {
it('should call success callback on valid path', function(done) {
- loadjs(['assets/file1.js'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- done();
+ loadjs(['assets/file1.js'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ done();
+ }
});
});
it('should call fail callback on invalid path', function(done) {
- loadjs(['assets/file-doesntexist.js'],
- function() {
- throw "Executed success callback";
- },
- function(pathsNotFound) {
- assert.equal(pathsNotFound.length, 1);
- assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
- done();
- });
+ loadjs(['assets/file-doesntexist.js'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(pathsNotFound) {
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ });
});
it('should call success callback on two valid paths', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs(['assets/file1.js', 'assets/file2.js'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
it('should call fail callback on one invalid path', function(done) {
- loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
- function() {
- throw "Executed success callback";
- },
- function(pathsNotFound) {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsNotFound.length, 1);
- assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
- done();
- });
+ loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(pathsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsNotFound.length, 1);
+ assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ }
+ });
});
@@ -75,10 +81,12 @@ describe('LoadJS tests', function() {
it('should create a bundle id and a callback inline', function(done) {
- loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
@@ -93,13 +101,16 @@ describe('LoadJS tests', function() {
loadjs('assets/file2.js', 'bundle6');
loadjs
- .ready('bundle5', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- bothDone();
- })
- .ready('bundle6', function() {
- assert.equal(pathsLoaded['file2.js'], true);
- bothDone();
+ .ready('bundle5', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ bothDone();
+ }})
+ .ready('bundle6', {
+ success: function() {
+ assert.equal(pathsLoaded['file2.js'], true);
+ bothDone();
+ }
});
});
@@ -108,10 +119,12 @@ describe('LoadJS tests', function() {
loadjs('assets/file1.js', 'bundle7');
loadjs('assets/file2.js', 'bundle8');
- loadjs.ready(['bundle7', 'bundle8'], function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready(['bundle7', 'bundle8'], {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
});
@@ -120,23 +133,26 @@ describe('LoadJS tests', function() {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
- loadjs.ready(['bundle9', 'bundle10'],
- function() {
- throw "Executed success callback";
- },
- function(depsNotFound) {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(depsNotFound.length, 1);
- assert.equal(depsNotFound[0], 'bundle10');
- done();
- });
+ loadjs.ready(['bundle9', 'bundle10'], {
+ success: function() {
+ throw "Executed success callback";
+ },
+ fail: function(depsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(depsNotFound.length, 1);
+ assert.equal(depsNotFound[0], 'bundle10');
+ done();
+ }
+ });
});
it('should execute callbacks on .done()', function(done) {
// add handler
- loadjs.ready('plugin1', function() {
- done();
+ loadjs.ready('plugin1', {
+ success: function() {
+ done();
+ }
});
// execute done
@@ -149,8 +165,10 @@ describe('LoadJS tests', function() {
loadjs.done('plugin2');
// add handler
- loadjs.ready('plugin2', function() {
- done();
+ loadjs.ready('plugin2', {
+ success: function() {
+ done();
+ }
});
});
@@ -161,10 +179,12 @@ describe('LoadJS tests', function() {
// use 1 second delay to let files load
setTimeout(function() {
- loadjs.ready('bundle1', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready('bundle1', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
}, 1000);
});
@@ -172,10 +192,12 @@ describe('LoadJS tests', function() {
it('should allow bundle callbacks before definitions', function(done) {
// define callback
- loadjs.ready('bundle2', function() {
- assert.equal(pathsLoaded['file1.js'], true);
- assert.equal(pathsLoaded['file2.js'], true);
- done();
+ loadjs.ready('bundle2', {
+ success: function() {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsLoaded['file2.js'], true);
+ done();
+ }
});
// use 1 second delay
@@ -184,6 +206,47 @@ describe('LoadJS tests', function() {
}, 1000);
});
+
+ it('should support async false', function(done) {
+ var numCompleted = 0,
+ numTests = 20,
+ paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
+
+ // run tests sequentially
+ var testFn = function(paths) {
+ loadjs(paths, {
+ success: function() {
+ var f1 = paths[0].replace('assets/', '');
+ var f2 = paths[1].replace('assets/', '');
+
+ // check load order
+ assert.isTrue(pathsLoaded[f1]);
+ assert.isFalse(pathsLoaded[f2]);
+
+ // increment tests
+ numCompleted += 1;
+
+ if (numCompleted === numTests) {
+ // exit
+ done();
+ } else {
+ // reset register
+ pathsLoaded = {};
+
+ // run test again
+ paths.reverse();
+ testFn(paths);
+ }
+ },
+ async: false
+ });
+ }
+
+ // run tests
+ testFn(paths);
+ });
+
+
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
@@ -192,15 +255,16 @@ describe('LoadJS tests', function() {
xit('it should report ad blocked scripts as missing', function(done) {
var blockedScript = 'https://www.googletagservices.com/tag/js/gpt.js';
- loadjs([blockedScript, 'assets/file1.js'],
- function() {
+ loadjs([blockedScript, 'assets/file1.js'], {
+ success: function() {
throw "Executed success callback";
},
- function(pathsNotFound) {
+ fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
done();
- });
+ }
+ });
});
});
| 131 | Modifies API, adds support for async: false, bumps version number | 67 | .js | js | mit | muicss/loadjs |
10066835 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
* - `Model` A model constructor to use (must have `.toJSON()`)
*
* @param {Object} options
*/
module.exports = function(options) {
/**
* Shortcut method for
* creating lazy views.
*
* @param {Object} options
* @return {Module}
*/
function fm(options) {
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
}
fm.create = module.exports;
fm.Model = options.Model;
fm.Events = events;
fm.Module = mod(fm);
fm.define = define(fm);
fm.util = utils;
fm.modules = {};
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
this.classes = this.classes || options.classes || [];
this.helpers = this.helpers || options.helpers || [];
this.template = this.getTemplate();
this._lookup = {};
this._children = [];
// Use the model passed in,
// or create a model from
// the data passed in.
* @api private
*/
View.prototype.attachHelper = function(helper) {
// Allow helpers to be passed in as
// string references to earlier registered
// helpers, or passed in directly as a function.
* @api private
*/
View.prototype._addLookup = function(child) {
this._lookup[child.id()] = child;
this._lookup[child._module] = this._lookup[child._module] || [];
this._lookup[child._module].push(child);
};
/**
* @api private
*/
View.prototype._removeLookup = function(child) {
var index = this._lookup[child._module].indexOf(child);
this._lookup[child._module].splice(index, 1);
delete this._lookup[child._id];
};
/**
* @api public
*/
View.prototype.id = function(id) {
return id
? this.module(id)
: this._id;
};
/**
* @deprecated
*/
View.prototype.child = function(query) {
var child = this._lookup[query];
if (child) return child[0] || child;
};
View.prototype.module = function(key) {
var child;
if (!key) return this._module;
child = this._lookup[key];
if (child) return child[0] || child;
return this.each(function(view) {
return view.child(key);
});
};
/**
*
* @param {undefined|String|Function} query
* @return {Array}
*/
View.prototype.children = function(query) {
// Get the direct children
// that match this query
return this._lookup[query] || [];
};
View.prototype.modules = function(key) {
// Get the direct children
// that match this query
var list = this._lookup[key] || [];
// Then loop each child and run the
// same opperation, appending the result
// onto the list.
this.each(function(view) {
list = list.concat(view.children(key));
});
return list;
};
/**
* Calls the passed function
this.destroyed = true;
// Clear references
this.el = this.model = this.parent = this._lookup = this._module = this._id = null;
};
// Empty methods you can overwrite
* Destroys all children.
*
* @return {View}
*/
View.prototype.empty = function() {
var children = this.children();
<MSG> Module and id lookups stored seperately
<DFF> @@ -256,9 +256,13 @@
this.classes = this.classes || options.classes || [];
this.helpers = this.helpers || options.helpers || [];
this.template = this.getTemplate();
- this._lookup = {};
this._children = [];
+ // Create id and module
+ // lookup objects
+ this._ids = {};
+ this._modules = {};
+
// Use the model passed in,
// or create a model from
// the data passed in.
@@ -281,6 +285,7 @@
* @api private
*/
View.prototype.attachHelper = function(helper) {
+
// Allow helpers to be passed in as
// string references to earlier registered
// helpers, or passed in directly as a function.
@@ -364,9 +369,13 @@
* @api private
*/
View.prototype._addLookup = function(child) {
- this._lookup[child.id()] = child;
- this._lookup[child._module] = this._lookup[child._module] || [];
- this._lookup[child._module].push(child);
+
+ // Add a lookup for module
+ this._modules[child._module] = this._modules[child._module] || [];
+ this._modules[child._module].push(child);
+
+ // Add a lookup for id
+ this._ids[child.id()] = child;
};
/**
@@ -377,9 +386,13 @@
* @api private
*/
View.prototype._removeLookup = function(child) {
- var index = this._lookup[child._module].indexOf(child);
- this._lookup[child._module].splice(index, 1);
- delete this._lookup[child._id];
+
+ // Remove the module lookup
+ var index = this._modules[child._module].indexOf(child);
+ this._modules[child._module].splice(index, 1);
+
+ // Remove the id lookup
+ delete this._ids[child._id];
};
/**
@@ -419,9 +432,55 @@
* @api public
*/
View.prototype.id = function(id) {
- return id
- ? this.module(id)
- : this._id;
+ if (!id) return this._id;
+
+ var child = this._ids[id];
+ if (child) return child;
+
+ return this.each(function(view) {
+ return view.id(id);
+ });
+ };
+
+ /**
+ * Returns the first descendent
+ * View with the passed module type.
+ *
+ * @param {String} key
+ * @return {View}
+ */
+ View.prototype.module = function(key) {
+ if (!key) return this._module;
+
+ var view = this._modules[key];
+ if (view) return view[0];
+
+ return this.each(function(view) {
+ return view.module(key);
+ });
+ };
+
+ /**
+ * Returns a list of descendent
+ * Views that match the module
+ * type given (Similar to
+ * Element.querySelector();).
+ *
+ * @param {String} key
+ * @return {Array}
+ * @api public
+ */
+ View.prototype.modules = function(key) {
+ var list = this._modules[key] || [];
+
+ // Then loop each child and run the
+ // same opperation, appending the result
+ // onto the list.
+ this.each(function(view) {
+ list = list.concat(view.modules(key));
+ });
+
+ return list;
};
/**
@@ -438,21 +497,8 @@
* @deprecated
*/
View.prototype.child = function(query) {
- var child = this._lookup[query];
- if (child) return child[0] || child;
- };
-
- View.prototype.module = function(key) {
- var child;
-
- if (!key) return this._module;
-
- child = this._lookup[key];
+ var child = this._modules[query] || this._ids[query];
if (child) return child[0] || child;
-
- return this.each(function(view) {
- return view.child(key);
- });
};
/**
@@ -471,6 +517,7 @@
*
* @param {undefined|String|Function} query
* @return {Array}
+ * @depricated
*/
View.prototype.children = function(query) {
@@ -480,24 +527,11 @@
// Get the direct children
// that match this query
- return this._lookup[query] || [];
+ return this._modules[query]
+ || this._ids[query]
+ || [];
};
- View.prototype.modules = function(key) {
-
- // Get the direct children
- // that match this query
- var list = this._lookup[key] || [];
-
- // Then loop each child and run the
- // same opperation, appending the result
- // onto the list.
- this.each(function(view) {
- list = list.concat(view.children(key));
- });
-
- return list;
- };
/**
* Calls the passed function
@@ -755,7 +789,7 @@
this.destroyed = true;
// Clear references
- this.el = this.model = this.parent = this._lookup = this._module = this._id = null;
+ this.el = this.model = this.parent = this._modules = this._module = this._ids = this._id = null;
};
// Empty methods you can overwrite
@@ -802,6 +836,7 @@
* Destroys all children.
*
* @return {View}
+ * @api public
*/
View.prototype.empty = function() {
var children = this.children();
| 76 | Module and id lookups stored seperately | 41 | .js | js | mit | ftlabs/fruitmachine |
10066836 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066837 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066838 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066839 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066840 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066841 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066842 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066843 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066844 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066845 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066846 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066847 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066848 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10066849 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace));
KeyBindings.Add(
TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift,
Key.Back)); // make Shift-Backspace do the same as plain backspace
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Add null check in OnIndentSelection() #122
https://github.com/icsharpcode/AvalonEdit/pull/122
<DFF> @@ -729,7 +729,7 @@ namespace AvaloniaEdit.Editing
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
- if (textArea?.Document != null)
+ if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
| 1 | Add null check in OnIndentSelection() #122 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.