package com.asparck.eclipse.multicursor.hacks;

import java.lang.reflect.Method;

import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.AbstractTextEditor;

import com.asparck.eclipse.multicursor.Logger;

/**
 * Uses hacky reflection techniques to find the source viewer for a given thing.
 */
public class ISourceViewerFinder {
	private static final Logger logger = Logger.create(ISourceViewerFinder.class);

	public static ISourceViewer fromEditorPart(IEditorPart editorPart) {
		if (editorPart instanceof AbstractTextEditor) {
			return fromAbstractTextEditor((AbstractTextEditor) editorPart);
		} else {
			logger.info("Unable to get ISourceViewer from " + editorPart + " of type "
					+ editorPart.getClass().getCanonicalName());
			return null;
		}
	}

	/**
	 * Relies on protected final method {@link AbstractTextEditor#getSourceViewer()}.
	 */
	private static ISourceViewer fromAbstractTextEditor(AbstractTextEditor editor) {
		try {
			Method getSourceViewerMethod = null;
			Class<?> clazz = editor.getClass();
			while (clazz != null && getSourceViewerMethod == null) {
				if (clazz.equals(AbstractTextEditor.class)) {
					getSourceViewerMethod = clazz.getDeclaredMethod("getSourceViewer");
				} else {
					clazz = clazz.getSuperclass();
				}
			}
			if (getSourceViewerMethod == null) {
				throw new RuntimeException();
			}
			getSourceViewerMethod.setAccessible(true);
			ISourceViewer result = (ISourceViewer) getSourceViewerMethod.invoke(editor);
			return result;
		} catch (Exception e) {
			logger.error("Failed to acquire ISourceViewer via reflection", e);
			return null;
		}
	}

}

@@ -162,16 +162,64 @@
 orPart;%0A
+import org.eclipse.ui.part.MultiPageEditorPart;%0A
 import o
@@ -593,22 +593,251 @@
 %7B%0A%09%09
-if (editorPart
+Object activeEditor = editorPart;%0A%09%09if (editorPart instanceof MultiPageEditorPart) %7B%0A%09%09%09MultiPageEditorPart multiPageEditorPart = (MultiPageEditorPart) editorPart;%0A%09%09%09activeEditor = multiPageEditorPart.getSelectedPage();%0A%09%09%7D%0A%09%09if (activeEditor
  ins
@@ -920,26 +920,28 @@
 Editor) 
-e
+activeE
 ditor
-Part
 );%0A%09%09%7D e
@@ -1009,17 +1009,22 @@
 itorPart
- 
+%0A%09%09%09%09%09
 + %22 of t
@@ -1028,22 +1028,17 @@
 f type %22
-%0A%09%09%09%09%09
+ 
 + editor

Support for multipage editors (e.g XML Editor)