1 /*******************************************************************************
2 * Copyright (c) 2000, 2004 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.ui.actions;
13 import java.util.ResourceBundle;
15 import net.sourceforge.phpdt.core.JavaCore;
16 import net.sourceforge.phpdt.core.formatter.DefaultCodeFormatterConstants;
17 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
18 import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner;
19 import net.sourceforge.phpdt.internal.ui.text.JavaIndenter;
20 import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager;
21 import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager.UndoSpec;
22 import net.sourceforge.phpdt.internal.ui.text.phpdoc.JavaDocAutoIndentStrategy;
23 import net.sourceforge.phpdt.ui.PreferenceConstants;
24 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
25 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
27 import org.eclipse.core.runtime.IStatus;
28 import org.eclipse.core.runtime.Status;
29 import org.eclipse.jface.text.Assert;
30 import org.eclipse.jface.text.BadLocationException;
31 import org.eclipse.jface.text.DocumentCommand;
32 import org.eclipse.jface.text.IDocument;
33 import org.eclipse.jface.text.IRegion;
34 import org.eclipse.jface.text.IRewriteTarget;
35 import org.eclipse.jface.text.ITextSelection;
36 import org.eclipse.jface.text.ITypedRegion;
37 import org.eclipse.jface.text.Position;
38 import org.eclipse.jface.text.Region;
39 import org.eclipse.jface.text.TextSelection;
40 import org.eclipse.jface.text.TextUtilities;
41 import org.eclipse.jface.text.source.ISourceViewer;
42 import org.eclipse.jface.viewers.ISelection;
43 import org.eclipse.jface.viewers.ISelectionProvider;
44 import org.eclipse.swt.custom.BusyIndicator;
45 import org.eclipse.swt.widgets.Display;
46 import org.eclipse.text.edits.MalformedTreeException;
47 import org.eclipse.text.edits.ReplaceEdit;
48 import org.eclipse.text.edits.TextEdit;
49 import org.eclipse.ui.IEditorInput;
50 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
51 import org.eclipse.ui.texteditor.IDocumentProvider;
52 import org.eclipse.ui.texteditor.ITextEditor;
53 import org.eclipse.ui.texteditor.ITextEditorExtension3;
54 import org.eclipse.ui.texteditor.TextEditorAction;
57 * Indents a line or range of lines in a Java document to its correct position.
58 * No complete AST must be present, the indentation is computed using
59 * heuristics. The algorith used is fast for single lines, but does not store
60 * any information and therefore not so efficient for large line ranges.
62 * @see net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner
63 * @see net.sourceforge.phpdt.internal.ui.text.JavaIndenter
66 public class IndentAction extends TextEditorAction {
68 /** The caret offset after an indent operation. */
69 private int fCaretOffset;
72 * Whether this is the action invoked by TAB. When <code>true</code>,
73 * indentation behaves differently to accomodate normal TAB operation.
75 private final boolean fIsTabAction;
78 * Creates a new instance.
83 * the prefix to use for keys in <code>bundle</code>
87 * whether the action should insert tabs if over the indentation
89 public IndentAction(ResourceBundle bundle, String prefix,
90 ITextEditor editor, boolean isTabAction) {
91 super(bundle, prefix, editor);
92 fIsTabAction = isTabAction;
96 * @see org.eclipse.jface.action.Action#run()
99 // update has been called by the framework
100 if (!isEnabled() || !validateEditorInputState())
103 ITextSelection selection = getSelection();
104 final IDocument document = getDocument();
106 if (document != null) {
108 final int offset = selection.getOffset();
109 final int length = selection.getLength();
110 final Position end = new Position(offset + length);
111 final int firstLine, nLines;
115 document.addPosition(end);
116 firstLine = document.getLineOfOffset(offset);
117 // check for marginal (zero-length) lines
118 int minusOne = length == 0 ? 0 : 1;
119 nLines = document.getLineOfOffset(offset + length - minusOne)
121 } catch (BadLocationException e) {
122 // will only happen on concurrent modification
123 PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin
124 .getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$
128 Runnable runnable = new Runnable() {
130 IRewriteTarget target = (IRewriteTarget) getTextEditor()
131 .getAdapter(IRewriteTarget.class);
132 if (target != null) {
133 target.beginCompoundChange();
134 target.setRedraw(false);
138 JavaHeuristicScanner scanner = new JavaHeuristicScanner(
140 JavaIndenter indenter = new JavaIndenter(document,
142 boolean hasChanged = false;
143 for (int i = 0; i < nLines; i++) {
144 hasChanged |= indentLine(document, firstLine + i,
145 offset, indenter, scanner);
148 // update caret position: move to new position when
149 // indenting just one line
150 // keep selection when indenting multiple
151 int newOffset, newLength;
153 newOffset = fCaretOffset;
155 } else if (nLines > 1) {
157 newLength = end.getOffset() - offset;
159 newOffset = fCaretOffset;
163 // always reset the selection if anything was replaced
164 // but not when we had a singleline nontab invocation
166 && (hasChanged || newOffset != offset || newLength != length))
167 selectAndReveal(newOffset, newLength);
169 document.removePosition(end);
170 } catch (BadLocationException e) {
171 // will only happen on concurrent modification
172 PHPeclipsePlugin.log(new Status(IStatus.ERROR,
173 PHPeclipsePlugin.getPluginId(), IStatus.OK,
174 "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
178 if (target != null) {
179 target.endCompoundChange();
180 target.setRedraw(true);
187 Display display = getTextEditor().getEditorSite()
188 .getWorkbenchWindow().getShell().getDisplay();
189 BusyIndicator.showWhile(display, runnable);
197 * Selects the given range on the editor.
200 * the selection offset
202 * the selection range
204 private void selectAndReveal(int newOffset, int newLength) {
205 Assert.isTrue(newOffset >= 0);
206 Assert.isTrue(newLength >= 0);
207 ITextEditor editor = getTextEditor();
208 if (editor instanceof PHPEditor) {
209 ISourceViewer viewer = ((PHPEditor) editor).getViewer();
211 viewer.setSelectedRange(newOffset, newLength);
213 // this is too intrusive, but will never get called anyway
214 getTextEditor().selectAndReveal(newOffset, newLength);
219 * Indents a single line using the java heuristic scanner. Javadoc and
220 * multiline comments are indented as specified by the
221 * <code>JavaDocAutoIndentStrategy</code>.
226 * the line to be indented
232 * the heuristic scanner
233 * @return <code>true</code> if <code>document</code> was modified,
234 * <code>false</code> otherwise
235 * @throws BadLocationException
236 * if the document got changed concurrently
238 private boolean indentLine(IDocument document, int line, int caret,
239 JavaIndenter indenter, JavaHeuristicScanner scanner)
240 throws BadLocationException {
241 IRegion currentLine = document.getLineInformation(line);
242 int offset = currentLine.getOffset();
243 int wsStart = offset; // where we start searching for non-WS; after
244 // the "//" in single line comments
246 String indent = null;
247 if (offset < document.getLength()) {
248 ITypedRegion partition = TextUtilities.getPartition(document,
249 IPHPPartitions.PHP_PARTITIONING, offset, true);
250 String type = partition.getType();
251 if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT)
252 || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) {
254 // TODO this is a hack
256 // new JavaDocAutoIndentStrategy().indentLineAtOffset(document,
263 IRegion previousLine = document
264 .getLineInformation(line - 1);
265 start = previousLine.getOffset() + previousLine.getLength();
268 DocumentCommand command = new DocumentCommand() {
270 command.text = "\n"; //$NON-NLS-1$
271 command.offset = start;
272 new JavaDocAutoIndentStrategy(IPHPPartitions.PHP_PARTITIONING)
273 .customizeDocumentCommand(document, command);
275 while (to < command.text.length()
276 && Character.isWhitespace(command.text.charAt(to)))
278 indent = command.text.substring(1, to);
280 } else if (!fIsTabAction && partition.getOffset() == offset
281 && type.equals(IPHPPartitions.PHP_SINGLELINE_COMMENT)) {
283 // line comment starting at position 0 -> indent inside
285 while (slashes < document.getLength() - 1
286 && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$
289 wsStart = offset + slashes;
291 StringBuffer computed = indenter.computeIndentation(offset);
292 int tabSize = PHPeclipsePlugin
294 .getPreferenceStore()
296 AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
297 while (slashes > 0 && computed.length() > 0) {
298 char c = computed.charAt(0);
300 if (slashes > tabSize)
309 computed.deleteCharAt(0);
312 indent = document.get(offset, wsStart - offset) + computed;
317 // standard java indentation
318 if (indent == null) {
319 StringBuffer computed = indenter.computeIndentation(offset);
320 if (computed != null)
321 indent = computed.toString();
323 indent = new String();
327 // get current white space
328 int lineLength = currentLine.getLength();
329 int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart,
330 offset + lineLength);
331 if (end == JavaHeuristicScanner.NOT_FOUND)
332 end = offset + lineLength;
333 int length = end - offset;
334 String currentIndent = document.get(offset, length);
336 // if we are right before the text start / line end, and already after
337 // the insertion point
338 // then just insert a tab.
339 if (fIsTabAction && caret == end
340 && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) {
341 String tab = getTabEquivalent();
342 document.replace(caret, 0, tab);
343 fCaretOffset = caret + tab.length();
347 // set the caret offset so it can be used when setting the selection
348 if (caret >= offset && caret <= end)
349 fCaretOffset = offset + indent.length();
353 // only change the document if it is a real change
354 if (!indent.equals(currentIndent)) {
355 String deletedText = document.get(offset, length);
356 document.replace(offset, length, indent);
359 && indent.length() > currentIndent.length()
360 && PHPeclipsePlugin.getDefault().getPreferenceStore()
362 PreferenceConstants.EDITOR_SMART_BACKSPACE)) {
363 ITextEditor editor = getTextEditor();
364 if (editor != null) {
365 final SmartBackspaceManager manager = (SmartBackspaceManager) editor
366 .getAdapter(SmartBackspaceManager.class);
367 if (manager != null) {
369 // restore smart portion
370 ReplaceEdit smart = new ReplaceEdit(offset, indent
371 .length(), deletedText);
373 final UndoSpec spec = new UndoSpec(offset
374 + indent.length(), new Region(caret, 0),
375 new TextEdit[] { smart }, 2, null);
376 manager.register(spec);
377 } catch (MalformedTreeException e) {
379 PHPeclipsePlugin.log(new Status(IStatus.ERROR,
380 PHPeclipsePlugin.getPluginId(), IStatus.OK,
381 "Illegal smart backspace action", e)); //$NON-NLS-1$
393 * Returns the size in characters of a string. All characters count one,
394 * tabs count the editor's preference for the tab display
397 * the string to be measured.
400 private int whiteSpaceLength(String indent) {
405 int l = indent.length();
406 int tabSize = PHPeclipsePlugin
408 .getPreferenceStore()
410 AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH);
412 for (int i = 0; i < l; i++)
413 size += indent.charAt(i) == '\t' ? tabSize : 1;
419 * Returns a tab equivalent, either as a tab character or as spaces,
420 * depending on the editor and formatter preferences.
422 * @return a string representing one tab in the editor, never
425 private String getTabEquivalent() {
427 if (PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(
428 PreferenceConstants.EDITOR_SPACES_FOR_TABS)) {
429 int size = JavaCore.getPlugin().getPluginPreferences().getInt(
430 DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE);
431 StringBuffer buf = new StringBuffer();
432 for (int i = 0; i < size; i++)
434 tab = buf.toString();
436 tab = "\t"; //$NON-NLS-1$
442 * Returns the editor's selection provider.
444 * @return the editor's selection provider or <code>null</code>
446 private ISelectionProvider getSelectionProvider() {
447 ITextEditor editor = getTextEditor();
448 if (editor != null) {
449 return editor.getSelectionProvider();
455 * @see org.eclipse.ui.texteditor.IUpdate#update()
457 public void update() {
462 setEnabled(canModifyEditor() && isSmartMode()
463 && isValidSelection());
465 setEnabled(canModifyEditor() && !getSelection().isEmpty());
469 * Returns if the current selection is valid, i.e. whether it is empty and
470 * the caret in the whitespace at the start of a line, or covers multiple
473 * @return <code>true</code> if the selection is valid for an indent
476 private boolean isValidSelection() {
477 ITextSelection selection = getSelection();
478 if (selection.isEmpty())
481 int offset = selection.getOffset();
482 int length = selection.getLength();
484 IDocument document = getDocument();
485 if (document == null)
489 IRegion firstLine = document.getLineInformationOfOffset(offset);
490 int lineOffset = firstLine.getOffset();
492 // either the selection has to be empty and the caret in the WS at
494 // or the selection has to extend over multiple lines
496 return document.get(lineOffset, offset - lineOffset).trim()
499 // return lineOffset + firstLine.getLength() < offset + length;
500 return false; // only enable for empty selections for now
502 } catch (BadLocationException e) {
509 * Returns the smart preference state.
511 * @return <code>true</code> if smart mode is on, <code>false</code>
514 private boolean isSmartMode() {
515 ITextEditor editor = getTextEditor();
517 if (editor instanceof ITextEditorExtension3)
518 return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT;
524 * Returns the document currently displayed in the editor, or
525 * <code>null</code> if none can be obtained.
527 * @return the current document or <code>null</code>
529 private IDocument getDocument() {
531 ITextEditor editor = getTextEditor();
532 if (editor != null) {
534 IDocumentProvider provider = editor.getDocumentProvider();
535 IEditorInput input = editor.getEditorInput();
536 if (provider != null && input != null)
537 return provider.getDocument(input);
544 * Returns the selection on the editor or an invalid selection if none can
545 * be obtained. Returns never <code>null</code>.
547 * @return the current selection, never <code>null</code>
549 private ITextSelection getSelection() {
550 ISelectionProvider provider = getSelectionProvider();
551 if (provider != null) {
553 ISelection selection = provider.getSelection();
554 if (selection instanceof ITextSelection)
555 return (ITextSelection) selection;
559 return TextSelection.emptySelection();