How do I get the line of text under the cursor in a TextView in gtk#? - gtk#

I have a GTK# TextView and I want to read the line of text under the cursor. I don't see a single method that will do that, so I think I need to combine several method calls, like Buffer.GetText, Buffer.GetIterAtOffset, Buffer.CursorPosition, but it's not obvious to me what the right combination is.

TextIter are a bit odd to use. Buffer.CursorPosition gives you the current position.
It's easy to find the end of the line:
var end = Buffer.CursorPosition;
end.ForwardToLineEnd();
To get the first character, there's not symetrical method, so you might try:
var start = Buffer.CursorPosition;
start.BackwardChars(start.LineOffset); // LineOffset gives you the iter offset on the current line.

Related

Ace editor - how do I remove/reset indent?

I want to change the behavior of the editor such that when the user presses enter on an empty list bullet, their cursor position is reset to the start of the line (rather than leaving them at the indented amount).
I've tried:
aceEdit.moveCursorTo(rowToUpdate, 0)
aceEdit.getSession().indentRows(rowToUpdate, rowToUpdate, "")
aceEdit.getSession().replace(range(rowToUpdate, 0, rowToUpdate, 0), "")
However, all three of these leave the cursor at the previous indent level. How do I reset the indent level for the line?
Update: adding example.
* list
* list
* list
* <- user presses enter here
_
Cursor is where I placed the underscore above, and can't be reset programmatically to the start of the line using what I listed above. (User can backspace the indents to get back to the start.)
You can use editor.setOption("enableAutoIndent", false) to disable automatic indentation.
If you want a way to keep autoIndent in all cases except the list, try creating an issue on ace's github page
If you want to remove the indentation on particular line you can do
var range = ace.Range
var cursor = editor.getCursorPosition()
var line = editor.session.getLine(cursor.row)
var match = /^\s*\*\s*/
if (match) {
editor.session.replace(new Range(cursor.row, 0, cursor.row, cursor.column), "")
}
If you are making a custom mode, you can give it a custom $outdent and related methods - see MatchingBraceOutdent, for example. I think the full set of indentation-related Mode methods is:
getNextLineIndent
checkOutdent
autoOutdent

Dividing by half in ruby to create an effective calculator

For the past while I've been working on a calculator, but have run into problems when needing to divide by a half. I'll add the offending bit of code along with a loop to keep it open below.
on = true
while on == true do
half = 1.0 / 2.0
puts ("FUNCTION IN TESTING MODE, DO NOT EXPECT IT TO FUNCTION PROPERLY")
puts ("Area of a triangle")
print("What is the legnth of the base? ").to_i
base = gets.chomp("base")
print("\nWhat is the height? ")
height = gets.chomp("height").to_i
PreAreaT = base * height
AreaT = PreAreaT * half
puts("The area of the triangle is #{AreaT}")
end
So essentially, how on Earth do I get the program to display an answer, rather than outputting nothing for the answer?
EDIT:As it would turn out the code above is improperly done. I've spent nearly two weeks asking myself why it wouldn't work only to find I had .to_i after a print statement rather than the input.
Your to_i call is switched around here.
print("What is the legnth of the base? ").to_i
base = gets.chomp("base")
Should be the other way 'round.
print("What is the length of the base? ")
base = gets.chomp("base").to_i
Further, chomp will attempt to remove any occurrences of base or height from the string. Be sure that you're intention is to remove those occurrences; if you want to remove whitespace, you'll have to take a different approach.

Capitalize first letter of sentence in CKeditor

I wish to capitalize the first letter of a sentence, on-the-fly, as the user types the text in a CKEditor content instance.
The strategy consists in catching each keystroke and try to replace it when necessary, that is for instance, when the inserted character follows a dot and a space. I'm fine with catching the event, but can't find a way to parse characters surrounding the caret position:
var instance = CKEDITOR.instances.htmlarea
instance.document.getBody().on('keyup', function(event) {
console.log(event);
// Would like to parse here from the event object...
event.data.preventDefault();
});
Any help would be much appreciated including a strategy alternative.
You should use keydown event (close to what you proposed):
var editor = CKEDITOR.instances.editor1;
editor.document.getBody().on('keydown', function(event) {
if (event.data.getKeystroke() === 65 /*a*/ && isFirstLetter()) {
// insert 'A' instead of 'a'
editor.insertText('A');
event.data.preventDefault();
}
});
Now - how should isFirstLetter() look like?
You have to start from editor.getSelection().getRanges() to get caret position.
You're interested only in the first range from the collection.
To extract text content from before the caret use small trick:
move start of the range to the beginning of document: range.setStartAt( editor.document.getBody(), CKEDITOR.POSITION_AFTER_START ),
use CKEDITOR.dom.walker to traverse through DOM tree in source order,
collect text nodes and find out what's before caret (is it /\. $/) - remember that you have to skip inline tags and stop on block tags - hint: return false from guard function to stop traversing.
Example of how you can use walker on range:
var range, walker, node;
range = editor.getSelection().getRanges()[0];
range.setStartAt(editor.document.getBody(), CKEDITOR.POSITION_AFTER_START);
walker = new CKEDITOR.dom.walker(range);
walker.guard = function(node) {
console.log(node);
};
while (node = walker.previous()) {}
And now few sad things.
We assumed that selection is empty when you type - that doesn't have to be true. When selection is not collapsed (empty) then you'll have to manually remove its content before calling insertText. You can use range#deleteContents to do this.
But this is not all - after deleting range's content you have to place caret in correct position - this isn't trivial. Basically you can use range#select (on the range after deleteContents), but in some cases it can place caret in incorrect place - like between paragraphs. Fixing this is... is not doable without deeeeeeeep knowledge about HTML+editables+insertions+other things :).
This solution is not complete - you have to handle paste event, deleting content (one can delete words from the start of sentence), etc, etc.
I guess there are couple of other problems I didn't even thought about :P.
So this approach isn't realistic. If you still want to implement this feature I think that you should set timer and by traversing DOM (you can use walker on range containing entire document, or recently typed text (hard to find out where it is)) find all sentences starting from lower letter and fix them.
This is what worked for me in Ckeditor 4.
var editor = CKEDITOR.instances.editor1;
editor.document.getBody().on('keydown', function(event) {
if (event.data.getKeystroke() >= 65 && event.data.getKeystroke()<=91 && encodeURI(this.getText())=="%0A" && this.getText().length==1 ) {
//uppercase the char
editor.insertText(String.fromCharCode(event.data.getKeystroke()));
event.data.preventDefault();
}
});

ZPL - zebra: print justified text block without overwriting last line

I'm using the following command to print a justified text:
^FB1800,3,0,J^FT100,200^A0B,26,26^FH\^FDLONG TEXT TO BE PRINTED, WHICH DOESNT FIT IN ONLY 3 LINES...^FS
The command ^FB1800,3,0,J prints a field block in a width of 1800 dots, maximum 3 lines, justified.
The problem is that if the text exceeds the maximum number of lines, it overwrites the last line! :( That of course makes the text of the last line unreadable.
How can I avoid that? Does anybody know if is there a way to cut the exceeding text?
The documentation says exactly that this happens:
Text exceeding the maximum number of lines overwrites the last line. Changing the font size automatically increases or decreases the size of the block.
For reference: I'm using printer Zebra 220Xi4.
Any help would be appreciated. Thank you!
Take a look at the ^TB command. It is preferred over the ^FB command and truncates if the text exceeds the size defined in the TB params
I had just about the same problem, what fixed it in my case - although not the most elegant way - is to specify a higher number of maximum lines, and then formatting it in a way that only the first 3 are in the visible area.
In your case it would be for example ^FB1800,7,0,J instead of ^FB1800,3,0,J
This at least fixed it for me right away, because I print this text at the bottom of the label. If you need to have it somewhere in the middle or top, there might be some tricks with putting a (white) box on top of the overflow-area, since the Zebra printers seem to render before printing. Hope it helps.
Depending on the higher-level programming language you're using (assuming that you are), you could accomplish the same thing (truncate the text to be printed to a specified number of characters) with code like this (C# shown here):
public void PrintLabel(string price, string description, string barcode)
{
const int MAX_CAPS_DESC_LEN = 21;
const int MAX_LOWERCASE_DESC_LEN = 32;
try
{
bool descAllUpper = HHSUtils.IsAllUpper(description);
if (descAllUpper)
{
if (description.Length > MAX_CAPS_DESC_LEN)
{
description = description.Substring(0, MAX_CAPS_DESC_LEN);
}
}
else // not all upper
{
if (description.Length > MAX_LOWERCASE_DESC_LEN)
{
description = description.Substring(0, MAX_LOWERCASE_DESC_LEN);
}
}
. . .
This is what I'm using; is there any reason to prefer the "raw" ^TB command over this?

How to position editbox's cursor in shoes?

Shoes is very handy GUI tool. I would like to do a search form so that a user is helped to navigate through larger texts for editing. For this I need to move the cursor within an editbox element.
Here you'll see my question in code:
Shoes.app do
stack do
p=para "After pressing 'search' a question will arise"
box=edit_box
box.text="One\nof\nthe\nmost\nstriking\ndifferences\nbetween\na\ncat\nand\na\nlie\nis\nthat\na\ncat\nhas\nonly\nnine lives."
flow :margin_top=>0.1 do
search=edit_line
button("search") do
pos=box.text.index search.text
y = box.text[0..pos].split.size-1 if pos
if not y.nil?
#For example if you searched "only" then
#cursor should jump/scroll to line 17.
#
#Anything there for cursor positioning,
#like: box.cursor=[0,y]
#
p.text="How can I move editbox's cursor in line #{y+1}?"
else
alert "'#{search.text}' not found"
end
end
end
end
end
Is there is any way to change cursor's position of an editbox? If not, do you know an alternative way of implementation?
Unfortunately, Shoes doesn't seem to provide any way to do that. These are the only methods defined on EditBox (it inherits from Native, which has several methods, but again, none to reposition the cursor).
rb_define_method(cEditBox, "text", CASTHOOK(shoes_edit_box_get_text), 0);
rb_define_method(cEditBox, "text=", CASTHOOK(shoes_edit_box_set_text), 1);
rb_define_method(cEditBox, "draw", CASTHOOK(shoes_edit_box_draw), 2);
rb_define_method(cEditBox, "change", CASTHOOK(shoes_control_change), -1);
http://github.com/why/shoes/blob/cea39a8bf9a5b7057b1824a9fab868d1f8609d69/shoes/ruby.c

Resources