|
From: <mit...@t-...> - 2014-03-12 20:18:33
|
Hello,
Here is my first macro. First time i saw and start writing macros
was two days ago.
I always like to keep my files/code clean. So i wrote
macro which will take care of it for me before it saves file.
Since i use
selectAll() to clean buffer, it will move caret to the end of buffer. Which
i didn't like. So now it will move caret back to pre-clean position.
Clean
process will first indent and then remove trailing white space in
buffer.
If caret is in trailing white space it will move it to the end of
the line after cleaning.
For new empty files it will show custom macro
error "Empty buffer. Nothing to clean/save."
I commented my code, so it
should clear things up a bit.
I thought it might be useful to others, so
here it is.
Best regards,
Mitja
CODE:
/*
* Clean_Save.bsh - a BeanShell
macro script for the jEdit text editor
* Indents and removes trailing white
space for all lines and returns caret to position prior cleaning.
*
Copyright (C) 2014 Mitja Zupanič
*
* Done: Clean_Save.bsh 2014-03-12
21:07
*
* P.S.: If you don't want to use Indent, comment out lines #39 and
#40.
* So it will only clean trailing white
space.
*/
if(textArea.getBufferLength() >= 1){
if(buffer.isReadOnly()){
Macros.error(view, "Buffer is read-only.");
}
else{
line_count =
textArea.getLineCount();
current_line = textArea.getCaretLine(); // Caret
line before pre-Clean
caret_pos = textArea.getCaretPosition(); // Buffer
caret position pre-Clean
if(line_count == 1){ // Check if buffer is empty
- including buffer with only white space. ...
textArea.goToEndOfCode(true); // ... Checking only buffers with one line.
if(textArea.getCaretPosition() == 0){
textArea.setCaretPosition(caret_pos);
Macros.error(view, "Empty buffer.
Nothing to clean/save.");
break;
}
else{
textArea.setCaretPosition(caret_pos);
}
}
CP1 =
textArea.getLineStartOffset(current_line); // Start of line Caret position
pre-Clean
textArea.goToEndOfWhiteSpace(true); // Needed for chekcing if
caret is in trailing white space
trail_start =
textArea.getCaretPosition();
textArea.selectAll(); // Select all
textArea.indentSelectedLines(); // Indent all
textArea.selectAll(); //
Select all
textArea.removeTrailingWhiteSpace(); // Clean all
CP2 =
textArea.getLineStartOffset(current_line); // Start of line Caret position
post-Clean
/*
* Difference between "CP1" and "CP2" is subtracted from
"caret_pos" (buffer caret position) or "trail_start".
* This way we can
set pre-Clean caret position (relating to string/content, not caret
position integer)
*/
if(trail_start |