PageRenderTime 193ms CodeModel.GetById 171ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 1ms

/bundles/plugins-trunk/TextTools/TextToolsBlockHandling.java

#
Java | 315 lines | 160 code | 14 blank | 141 comment | 37 complexity | 0e6c04c99053794e4ba317afa33e34fc MD5 | raw file
  1/*
  2 * TextToolsBlockHandling.java - a Java class for the jEdit text editor
  3 * :tabSize=8:indentSize=8:noTabs=false:
  4 * :folding=explicit:collapseFolds=1:
  5 *
  6 * Copyright (C) 2002 Rudolf Widmann
  7 * Rudi.Widmann@web.de
  8 *
  9 * 1) inserts or fills a given string or number into a selection
 10 * 2) converts spaces to tabs
 11 *	based on:
 12 *	- TextUtilities.spacesToTabs
 13 *	- MiscUtilities.createWhiteSpace
 14 *
 15 * Checked for jEdit 4.0 API
 16 *
 17 * This program is free software; you can redistribute it and/or
 18 * modify it under the terms of the GNU General Public License
 19 * as published by the Free Software Foundation; either version 2
 20 * of the License, or any later version.
 21 *
 22 * This program is distributed in the hope that it will be useful,
 23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 25 * GNU General Public License for more details.
 26 *
 27 * You should have received a copy of the GNU General Public License
 28 * along with this program; if not, write to the Free Software
 29 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 30 */
 31
 32//{{{ Imports
 33import java.util.*;
 34
 35import org.gjt.sp.jedit.BeanShell;
 36import org.gjt.sp.jedit.buffer.JEditBuffer;
 37import org.gjt.sp.jedit.EditPlugin;
 38import org.gjt.sp.jedit.GUIUtilities;
 39import org.gjt.sp.jedit.jEdit;
 40import org.gjt.sp.jedit.MiscUtilities;
 41import org.gjt.sp.jedit.TextUtilities;
 42import org.gjt.sp.jedit.View;
 43import org.gjt.sp.jedit.textarea.JEditTextArea;
 44import org.gjt.sp.jedit.textarea.Selection;
 45import org.gjt.sp.util.Log;
 46import org.gjt.sp.util.StandardUtilities;
 47
 48import java.awt.event.KeyListener;
 49import java.awt.event.KeyEvent;
 50import javax.swing.JDialog;
 51import javax.swing.JTextField;
 52import javax.swing.border.*;
 53//}}}
 54
 55public class TextToolsBlockHandling
 56{
 57	
 58	//{{{ doBlockAction() method
 59	public static void doBlockAction(
 60		View	view,
 61		int incrementValue,
 62		int insertValue,
 63		String insertText,
 64		boolean overwriteBlock,
 65		boolean increment,
 66		boolean leadingZeros)
 67	{
 68		BeanShellUtility bsu = new BeanShellUtility(view);
 69		JEditTextArea textArea = view.getTextArea();
 70		int startRange;
 71		int endRange;
 72		boolean trace=true;
 73		JEditBuffer buffer = view.getBuffer();
 74		/*********************************************************
 75		 * evaluate selection
 76		 *********************************************************/
 77		Selection[] sel = textArea.getSelection();
 78		int selCount = textArea.getSelectionCount();
 79		int selBegin;
 80		int selEnd;
 81		// check anything is selected
 82		if (selCount == 0 )
 83		{
 84			//Note: The TextToolsPlugin class now prevents 
 85			//this case from happening.
 86			
 87			selBegin = bsu.getVisibleRow(textArea.getCaretPosition());
 88			// Log.log(Log.DEBUG, BeanShell.class,"selBegin = "+selBegin);
 89			selEnd = selBegin + insertText.length();
 90			textArea.goToBufferEnd(true);
 91		} else {
 92			// get range, maybe different per line ico multiple/ rect selections
 93			// for several reasons, we take the width of the first selected line, and apply it to all selections
 94			// selBegin = bsu.getVisibleRow(sel[0].getStart());
 95			// selEnd = bsu.getVisibleRow(sel[0].getEnd(buffer, sel[0].getStartLine()));
 96			
 97			//Get the correct start column and end column of the selection.
 98			//Note: The TextToolsPlugin class ensures
 99			//that the selection is rectangular.
100			selBegin = ((Selection.Rect)sel[0]).getStartColumn(buffer);
101			selEnd = ((Selection.Rect)sel[0]).getEndColumn(buffer);
102		}
103		
104		/*********************************************************
105		 * check if only one line selected ==> select form cursor to eof
106		 *********************************************************/
107		if (selCount == 1 && (sel[0].getStartLine() == sel[0].getEndLine()))
108		{
109			//Note: The TextToolsPlugin now prevents 
110			//this case from happening.
111			if (trace)
112				Log.log(Log.DEBUG, TextToolsBlockHandling.class,"only one selection line");
113			textArea.setCaretPosition(sel[0].getStart());
114			textArea.goToBufferEnd(true);
115		}
116		/*********************************************************
117		 * check insert text matches selection
118		 *********************************************************/
119		int targetLen = selEnd - selBegin;
120		if (!increment && overwriteBlock) // insert shall match selection exactly
121		{
122			if (insertText.length() < targetLen)
123				insertText = insertText + StandardUtilities.createWhiteSpace(targetLen - insertText.length(), 0);
124			else if (insertText.length() > targetLen)
125				insertText = insertText.substring(0,targetLen);
126		}
127		/*********************************************************
128		 * prepare increment filling string
129		 *********************************************************/
130		String nullsBlanksString=null;
131		int currentIncValue=insertValue;
132		if (increment)
133		{
134			if (leadingZeros)
135			{
136				StringBuilder nulBuf = new StringBuilder("0000000000");
137				for (int s=10; s<targetLen;s+=10)
138					nulBuf.append("0000000000");
139				nullsBlanksString = nulBuf.toString();
140			} else {
141				nullsBlanksString = StandardUtilities.createWhiteSpace(targetLen, 0);
142			}
143		}
144		/*********************************************************
145		 * begin text manipulations
146		 *********************************************************/
147		int[] selLines = textArea.getSelectedLines();
148		String sourceString = insertText;
149		// Note: from now on, we don't need the selections
150		textArea.selectNone();  // reset selection
151		StringBuilder blankBuf = new StringBuilder("          ");
152		buffer.beginCompoundEdit();
153		ArrayList targetSelection = new ArrayList();  // collects Selection
154		for (int i=0;i<selLines.length;i++)
155		{
156			/*********************************************************
157			 * handle tabs: replace with spaces if tabs exist
158			 *********************************************************/
159			boolean isWithTabs = false;
160			if (buffer.getLineText(selLines[i]).indexOf("\t") != -1)
161			{
162				// line contains tabs
163				isWithTabs = true;
164				bsu.selectLine(selLines[i]);
165				textArea.tabsToSpaces();
166			}
167			/*********************************************************
168			 * calculate insert string
169			 *********************************************************/
170			if (increment) 
171			{
172				String valString = Integer.toString(currentIncValue);
173				String pfxString;
174				if (targetLen - valString.length() > 0) 
175				{
176					pfxString = nullsBlanksString.substring(0,targetLen - valString.length());
177				} else
178					pfxString = "";
179				if (currentIncValue < 0 && leadingZeros) 
180				{
181					// minus dash should be at beginning of zeros
182					sourceString = "-" + pfxString + valString.substring(1);
183				} else {
184					sourceString = pfxString + valString;
185				}
186				if (sourceString.length() > targetLen)
187					sourceString = sourceString.substring(sourceString.length() - targetLen);
188			}
189			/*********************************************************
190			 * check if linelength too short: add missing blanks
191			 *********************************************************/
192			int lineEndOffset = textArea.getLineEndOffset(selLines[i]);
193			int insertPos = textArea.getLineStartOffset(selLines[i])+selBegin;
194			int missingBlanks = insertPos - lineEndOffset+1; // +1'cause of <cr>
195			String prefixString = "";
196			if (missingBlanks > 0) 
197			{
198				while (blankBuf.length() < missingBlanks) blankBuf.append("          ");
199				prefixString = blankBuf.substring(0,missingBlanks);
200				insertPos = insertPos - missingBlanks;
201				// Log.log(Log.DEBUG, BeanShell.class,"*3 insertPos = "+insertPos);
202			}
203			/*********************************************************
204			 * finally, do modification
205			 *********************************************************/
206			if (overwriteBlock && lineEndOffset > 0) 
207			{
208				// dont remove chars that dont exist ==> calc remove len
209				int removeDecrement = insertPos +
210						       prefixString.length() + 
211						       sourceString.length() - 
212						       (lineEndOffset-1);
213				if (removeDecrement < 0) 
214					removeDecrement = 0;
215				buffer.remove(insertPos, prefixString.length() + sourceString.length() - removeDecrement);
216			}
217			buffer.insert(insertPos,prefixString+sourceString);
218
219			if (isWithTabs) 
220			{
221				// change back to tabs
222				bsu.selectLine(selLines[i]);
223				// Note: as long as there are bugs in 
224				//textArea.spacesToTabs, a local patch is used
225				textArea.spacesToTabs();
226			}
227			/*********************************************************
228			 * memorize selection
229			 *********************************************************/
230			int newBeginSelection = insertPos+prefixString.length();
231			if (newBeginSelection > buffer.getLength())
232				newBeginSelection = buffer.getLength();
233			int newEndSelection = insertPos+prefixString.length() + sourceString.length();
234			if (newEndSelection > buffer.getLength())
235				newEndSelection = buffer.getLength();
236			targetSelection.add(new Selection.Range(newBeginSelection, newEndSelection));
237			// textArea.addToSelection(new Selection.Rect(insertPos, insertPos+prefixString.length()+
238			// sourceString.length()));
239			if (increment)
240				currentIncValue += incrementValue;
241		}
242		/*********************************************************
243		 * set selection to changed chunks
244		 *********************************************************/
245		 Selection[] newSel = new Selection[targetSelection.size()];
246		 newSel = (Selection[])targetSelection.toArray(newSel);
247		 textArea.setSelection(newSel);
248		 buffer.endCompoundEdit();
249	} //}}}
250	
251	//{{{ getTempIntProperty() method
252	
253	String getTempIntProperty(String prop) 
254	{
255		String ret = jEdit.getProperty(prop);
256		if (ret == null) 
257			return "";
258		else
259			return ret;
260	} //}}}
261
262// this single line of code is the script's main routine
263// it calls the methods and exits
264// displayInsertFillDialog();
265
266/*
267	Macro index data (in DocBook format)
268 * - inserts or fills a given <source> into a <target box>
269 * - the source is either
270 *   * a string
271 *   * a number to be incremented
272 * - the target depends on the selection
273 *   * no selection
274 *   < in a selected area
275 *   <
276 * or all lines
277
278<listitem>
279    <para><filename>TextToolsBlockHandling.java</filename></para>
280    <abstract><para>
281	Inserts or replaces, fills or increments, a given string or number, into a selection block.
282	Dialog driven
283    </para>
284    </abstract>
285    <para>
286    Inserts or replaces, fills or increments, a given <quote>text</quote> into a <quote>target box</quote>
287    </para>
288    <para>When invoked, a dialog pops-up, with the fields:
289    * <quote>Text to be inserted</quote>: text you want to insert
290    * <quote>Increment</quote>: int value serving as increment
291    * <quote>Overwrite checkbox</quote>: checked: Overwrite selection, not checked: insert
292    * <quote>Leading Zeros checkbox</quote>: checked: Fill unused digits with nulls , not checked: fill with blanks
293    </para>
294    <para>
295    <quote>text</quote> is either:
296      * a string
297      * a number to be incremented
298    </para>
299    <para>
300    the <quote>target box</quote> depends on the selection:
301      * no selection: a box starting at the caret position till EOF, width of <quote>insert text</quote>
302      * selection in one line: a box starting at the caret position till EOF, width as selected
303      * rect selection: box as selected, width
304    </para>
305    <para>
306    If the insertion doesnot match the target box, it is filled with blanks, or cut.
307    </para>
308    <para>
309    Multiple selection is supported, but the width is according the the first selection
310    </para>
311</listitem>
312
313*/
314
315}