Index: TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/ColumnSelectionListener.java
===================================================================
--- TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/ColumnSelectionListener.java	(revision 3626)
+++ TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/ColumnSelectionListener.java	(revision 3627)
@@ -5,6 +5,7 @@
 import org.eclipse.swt.events.SelectionListener;
 import org.txm.rcp.StatusLine;
 import org.txm.rcp.messages.TXMUIMessages;
+import org.txm.statsengine.core.StatException;
 
 /**
  * The listener interface for receiving columnSelection events.
@@ -54,7 +55,13 @@
 	@Override
 	public void widgetSelected(SelectionEvent e) {
 		StatusLine.setMessage(TXMUIMessages.sortingColumn);
-		this.editor.sort(this.col, this.columnIndex);
-		StatusLine.setMessage(""); //$NON-NLS-1$
+		try {
+			this.editor.sort(this.col, this.columnIndex);
+			StatusLine.setMessage(""); //$NON-NLS-1$
+		} catch (Exception e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		}
+		
 	}
 }
Index: TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/LexicalTableEditor.java
===================================================================
--- TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/LexicalTableEditor.java	(revision 3626)
+++ TXM/trunk/org.txm.lexicaltable.rcp/src/org/txm/lexicaltable/rcp/editors/LexicalTableEditor.java	(revision 3627)
@@ -29,10 +29,15 @@
 
 import java.io.File;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.HashSet;
 import java.util.List;
 
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
 import org.eclipse.jface.viewers.TableViewer;
 import org.eclipse.jface.viewers.TableViewerColumn;
 import org.eclipse.jface.window.Window;
@@ -80,87 +85,87 @@
  * @author mdecorde
  */
 public class LexicalTableEditor extends TXMEditor<LexicalTable> {
-	
-	
+
+
 	public static final String ID = LexicalTableEditor.class.getName();
-	
+
 	/** The table. */
 	LexicalTable lexicalTable;
-	
+
 	// params
 	/** The line table viewer. */
 	TableViewer viewer;
-	
+
 	/** The form column. */
 	TableViewerColumn unitColumn;
-	
+
 	/** The freq column. */
 	TableViewerColumn freqColumn;
-	
+
 	/** The cols. */
 	private List<double[]> cols;
-	
+
 	/** The rows. */
 	private List<String> rows;
-	
+
 	/** The collist. */
 	List<Object> collist;
-	
+
 	/** The previous sorted col. */
 	private int previousSortedCol;
-	
+
 	boolean DEFAULTREVERSE = false;
-	
+
 	boolean reverse = DEFAULTREVERSE;
-	
-	
+
+
 	private Label infoLine;
-	
+
 	/**
 	 * Button to merge or delete some rows.
 	 */
 	protected Button mergeDeleteRowsButton;
-	
+
 	/**
 	 * Button to merge or delete some columns.
 	 */
 	protected Button mergeDeleteColumnsButton;
-	
-	
-	
+
+
+
 	// FIXME: SJ: viewer comparator tests
 	// /**
 	// * Viewer comparator for sorting.
 	// */
 	// protected LexicalTableLinesViewerComparator viewerComparator;
-	
-	
-	
+
+
+
 	/**
 	 * Unit property.
 	 */
 	@Parameter(key = TXMPreferences.UNIT_PROPERTY)
 	protected PropertiesComboViewer unitPropertyComboViewer;
-	
-	
+
+
 	/**
 	 * Minimum frequency filter spinner.
 	 */
 	@Parameter(key = TXMPreferences.F_MIN)
 	protected Spinner fMinSpinner;
-	
+
 	/**
 	 * Minimum frequency filter spinner.
 	 */
 	@Parameter(key = TXMPreferences.F_MAX)
 	protected Spinner fMaxSpinner;
-	
+
 	/**
 	 * Maximum numbers of lines spinner.
 	 */
 	@Parameter(key = TXMPreferences.V_MAX)
 	protected Spinner vMaxSpinner;
-	
+
 	/**
 	 * Creates the part control.
 	 *
@@ -169,14 +174,14 @@
 	 */
 	@Override
 	public void _createPartControl() {
-		
+
 		try {
 			lexicalTable = this.getResult();
-			
+
 			// Main parameters
 			GLComposite mainParametersArea = this.getMainParametersComposite();
 			mainParametersArea.getLayout().numColumns = 2;
-			
+
 			// unit property
 			new Label(mainParametersArea, SWT.NONE).setText(TXMCoreMessages.common_property);
 			ArrayList<WordProperty> availablesProperties = new ArrayList<>();
@@ -189,16 +194,16 @@
 					availablesProperties,
 					this.getResult().getProperty(),
 					false);
-			
+
 			// disable the property selection on Lexical table created from partition index
 			if (this.getResult().getParent() instanceof PartitionIndex) {
 				this.unitPropertyComboViewer.getCombo().setEnabled(false);
 			}
-			
-			
+
+
 			// Extended parameters
 			Composite extendedParametersArea = this.getExtendedParametersGroup();
-			
+
 			// FIXME: SJ: became useless? Apply button
 			// Button keepTop = new Button(extendedParametersArea, SWT.PUSH);
 			// keepTop.setText(LexicalTableUIMessages.LexicalTableEditor_4);
@@ -232,33 +237,33 @@
 			// public void widgetDefaultSelected(SelectionEvent e) {
 			// }
 			// });
-			
-			
+
+
 			// thresholds
 			ThresholdsGroup thresholdsGroup = new ThresholdsGroup(this.getExtendedParametersGroup(), SWT.NONE, this, true, true);
 			this.fMinSpinner = thresholdsGroup.getFMinSpinner();
 			this.fMaxSpinner = thresholdsGroup.getFMaxSpinner();
 			this.vMaxSpinner = thresholdsGroup.getVMaxSpinner();
 			this.vMaxSpinner.setMinimum(2); // LT won't work with 1 line only
-			
+
 			CQPCorpus corpus = getResult().getFirstParent(MainCorpus.class);
 			if (corpus != null) {
 				this.vMaxSpinner.setMaximum(corpus.getSize());
 				this.fMaxSpinner.setMaximum(corpus.getSize());
 				this.fMinSpinner.setMaximum(corpus.getSize());
 			}
-			
+
 			// Merge or delete columns button
 			mergeDeleteColumnsButton = new Button(extendedParametersArea, SWT.PUSH);
 			mergeDeleteColumnsButton.setText(LexicalTableUIMessages.mergeOrDeleteColumns);
 			mergeDeleteColumnsButton.addSelectionListener(new SelectionListener() {
-				
+
 				@Override
 				public void widgetSelected(SelectionEvent e) {
 					StatusLine.setMessage(LexicalTableUIMessages.mergingLines);
 					ArrayList<Object> selection = new ArrayList<>();
 					MergeDeleteDialog d = new MergeDeleteDialog(e.display.getActiveShell(), new ArrayList<>(collist), selection, -1);
-					
+
 					if (d.open() == Window.OK) {
 						List<Integer> colindices = new ArrayList<>();
 						for (int i = 0; i < collist.size(); i++) {
@@ -266,34 +271,34 @@
 								colindices.add(i);
 							}
 						}
-						
+
 						try {
-							
+
 							if (d.doMerge()) {
-								
+
 								int nrows = lexicalTable.getNRows();
-								
+
 								String newname = d.getMergeName();
-								
+
 								Log.fine(NLS.bind(LexicalTableUIMessages.mergeColsColonP0, colindices));
-								
+
 								double[] firstcol = cols.get(colindices.get(0));
-								
+
 								// merge selected cols into the first one
 								for (int i = 1; i < colindices.size(); i++) {
 									for (int j = 0; j < nrows; j++) {
 										firstcol[j] += cols.get(colindices.get(i))[j];
 									}
 								}
-								
+
 								// update first col of the Lexical table
 								for (int j = 0; j < nrows; j++) {
 									lexicalTable.getData().set(j, colindices.get(0), firstcol[j]);
 								}
-								
+
 								// and its name
 								lexicalTable.getColNames().setString(colindices.get(0), newname);
-								
+
 								// keep only the first col
 								List<Integer> coltodelete = colindices.subList(1, colindices.size());
 								lexicalTable.getData().removeCols(coltodelete);
@@ -304,7 +309,7 @@
 								for (String colname : lexicalTable.getColNames().asStringsArray()) {
 									collist.add(colname);
 								}
-								
+
 								Collections.sort(colindices);// update table viewer cols
 								for (int i = colindices.size() - 1; i >= 1; i--) {
 									viewer.getTable().getColumns()[colindices.get(i) + 3].dispose();// +3 = separator,
@@ -312,16 +317,16 @@
 								}
 								viewer.getTable().getColumns()[colindices.get(0) + 3].setText(newname);
 								compute(false);
-								
-								
+
+
 							}
 							// delete
 							else {
 								Log.fine(NLS.bind(LexicalTableUIMessages.deleteColsColonP0, colindices));
-								
+
 								lexicalTable.getData().removeCols(colindices);
 								lexicalTable.setAltered();
-								
+
 								collist = new ArrayList<>();
 								Vector colnames = lexicalTable.getColNames();
 								for (String colname : colnames.asStringsArray()) {
@@ -340,21 +345,21 @@
 						}
 					}
 					StatusLine.setMessage(""); //$NON-NLS-1$
-					
+
 				}
-				
+
 				@Override
 				public void widgetDefaultSelected(SelectionEvent e) {}
 			});
-			
+
 			// Merge or delete lines button
 			mergeDeleteRowsButton = new Button(extendedParametersArea, SWT.PUSH);
 			mergeDeleteRowsButton.setText(LexicalTableUIMessages.mergeOrDeleteRows);
 			mergeDeleteRowsButton.addSelectionListener(new SelectionListener() {
-				
+
 				@Override
 				public void widgetSelected(SelectionEvent e) {
-					
+
 					ArrayList<Object> selection = new ArrayList<>();
 					MergeDeleteDialog d = new MergeDeleteDialog(e.display
 							.getActiveShell(), new ArrayList<Object>(rows),
@@ -369,83 +374,91 @@
 							}
 						}
 						try {
-						
-						if (d.doMerge()) {
-							MergeLines.mergeLines(LexicalTableEditor.this, d.getMergeName(), rowindices);
-						}
-						else {
-							lexicalTable.getData().removeRows(rowindices);
-							compute(false);
-						}
-						lexicalTable.setAltered();
+
+							if (d.doMerge()) {
+								MergeLines.mergeLines(LexicalTableEditor.this, d.getMergeName(), rowindices);
+							}
+							else {
+								lexicalTable.getData().removeRows(rowindices);
+								compute(false);
+							}
+							lexicalTable.setAltered();
 						} catch(Exception ex) {
 							Log.warning(ex.getMessage());
 							Log.printStackTrace();
 						}
 					}
 				}
-				
+
 				@Override
 				public void widgetDefaultSelected(SelectionEvent e) {}
 			});
-			
+
 			// Result area
 			Composite resultArea = this.getResultArea();
-			
+
 			GridData gd = new GridData(GridData.FILL_BOTH);
 			gd.grabExcessVerticalSpace = true;
 			gd.grabExcessHorizontalSpace = true;
 			// gd.horizontalSpan = 2;
 			resultArea.setLayoutData(gd);
-			
+
 			viewer = new TableViewer(resultArea, SWT.VIRTUAL | SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER);
 			viewer.getTable().addKeyListener(new TableKeyListener(viewer));
 			viewer.getTable().setLinesVisible(true);
 			viewer.getTable().setHeaderVisible(true);
-			
-			
+
+			viewer.addSelectionChangedListener(new ISelectionChangedListener() {
+
+				@Override
+				public void selectionChanged(SelectionChangedEvent event) {
+					System.out.println("sel="+viewer.getStructuredSelection().toList());
+				}
+			});
+
+
 			// viewer.setContentProvider(ArrayContentProvider.getInstance());
-			
+
 			// FIXME: viewer comparator tests
 			// creates the viewer comparator
 			// this.viewerComparator = new LexicalTableLinesViewerComparator(Toolbox.getCollator(this.getResult()));
 			// viewer.setComparator(this.viewerComparator);
-			
+
 			// FIXME: we must use this line rather than the LineContentProvider class
 			// viewer.setContentProvider(ArrayContentProvider.getInstance());
 			viewer.setContentProvider(new LineContentProvider());
-			
-			
+
+
 			viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
-			
+
 			// first dummy column
 			TableViewerColumn nColumn = new TableViewerColumn(viewer, SWT.RIGHT);
 			nColumn.getColumn().setText(" "); //$NON-NLS-1$
-			
+
 			// property column
 			unitColumn = new TableViewerColumn(viewer, SWT.LEFT);
 			unitColumn.getColumn().addSelectionListener(new ColumnSelectionListener(this, unitColumn, -3));
 			// FIXME: viewer comparator tests
 			// viewerComparator.addSelectionAdapter(viewer, unitColumn.getColumn(), 1);
-			
+
 			// frequency column
 			freqColumn = new TableViewerColumn(viewer, SWT.LEFT);
 			freqColumn.getColumn().setText(TXMCoreMessages.common_frequency);
 			freqColumn.getColumn().addSelectionListener(new ColumnSelectionListener(this, freqColumn, -2));
 			// FIXME: viewer comparator tests
 			// viewerComparator.addSelectionAdapter(viewer, freqColumn.getColumn(), 2);
-			
+
 			// add a separator empty column
 			TableViewerColumn separatorColumn = new TableViewerColumn(viewer, SWT.NONE);
 			separatorColumn.getColumn().setResizable(false);
-			
+
 			// Register the context menu
 			TXMEditor.initContextMenu(this.viewer.getTable(), this.getSite(), this.viewer); // $NON-NLS-1$
-			
+
 			// adjust UI to the original sorting
 			viewer.getTable().setSortColumn(unitColumn.getColumn());
 			viewer.getTable().setSortDirection(SWT.UP);
-			
+
 			infoLine = new Label(getBottomToolbar().getParent(), SWT.NONE);
 		}
 		catch (Exception e) {
@@ -453,8 +466,8 @@
 			e.printStackTrace();
 		}
 	}
-	
-	
+
+
 	/**
 	 * 
 	 * @throws StatException
@@ -463,19 +476,19 @@
 	private void refreshColNames() throws StatException, CqiClientException {
 		TableColumn[] cols = viewer.getTable().getColumns();
 		String[] colnames = lexicalTable.getColNames().asStringsArray();
-		
+
 		for (int i = 0; i < cols.length; i++) {
 			cols[i].setText(colnames[i] + "T=" + lexicalTable.getPartition().getParts().get(i).getSize()); //$NON-NLS-1$
 		}
 	}
-	
+
 	@Override
 	public void setContentDescription(String desc) {
 		infoLine.setText(desc);
 		infoLine.update();
 		infoLine.getParent().layout();
 	}
-	
+
 	/**
 	 * Refreshes the description area.
 	 */
@@ -488,34 +501,34 @@
 			org.txm.utils.logger.Log.printStackTrace(e3);
 		}
 	}
-	
+
 	public void refreshTable() {
 		this.refreshTable(false);
 	}
-	
+
 	/**
 	 * Refreshes table.
 	 */
 	// FIXME: SJ: not optimized, need to mix the update/not update code and do not remove column each computing, only when needed
 	// FIXME: SJ: + usine à gaz... virer la variable "collist"
 	public void refreshTable(boolean update) {
-		
+
 		this.viewer.getControl().setRedraw(false);
-		
+
 		// removing old columns
 		for (int i = viewer.getTable().getColumnCount() - 2; i >= 3; i--) {
 			viewer.getTable().getColumns()[i].dispose();
 		}
-		
+
 		try {
-			
+
 			collist = new ArrayList<>();
-			
+
 			if (this.lexicalTable.getProperty() != null) {
 				unitColumn.getColumn().setText(this.lexicalTable.getProperty().getName());
 			}
-			
-			
+
+
 			// creating the columns
 			String[] colNames;
 			int[] colMargins = null;
@@ -528,11 +541,11 @@
 			else {
 				colNames = this.getResult().getPartition().getPartNames().toArray(new String[0]);
 			}
-			
-			
+
+
 			int MAX_NUMBER_OF_COLUMNS = RCPPreferences.getInstance().getInt(RCPPreferences.MAX_NUMBER_OF_COLUMNS);
 			for (int i = 0; i < colNames.length; i++) {
-				
+
 				if (i >= MAX_NUMBER_OF_COLUMNS) {
 					Log.warning(NLS.bind("Warning The number of columns exceeds {0} ({1}). the table has been cut. You can, change the maximum in the TXM > User preference page", MAX_NUMBER_OF_COLUMNS, colNames.length));
 					break;
@@ -541,58 +554,63 @@
 				column.getColumn().addSelectionListener(new ColumnSelectionListener(this, column, i));
 				// FIXME: viewer comparator tests
 				// viewerComparator.addSelectionAdapter(viewer, column.getColumn(), i + 2);
-				
+
 				String colName = colNames[i];
 				column.getColumn().setToolTipText(colName);
 				collist.add(colName);
-				
+
 				if (colMargins != null) {
 					colName += " t=" + colMargins[i]; //$NON-NLS-1$
 				}
-				
+
 				column.getColumn().setText(colName);
-				
-				
+
+
 			}
-			
+
 			// add a separator empty column
 			TableViewerColumn separatorColumn = new TableViewerColumn(viewer, SWT.NONE);
 			separatorColumn.getColumn().setResizable(false);
-			
+
 		}
 		catch (StatException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
-		
-		
+
+
 		if (this.lexicalTable.hasBeenComputedOnce()) {
 			LineLabelProvider labelprovider = new LineLabelProvider(this.lexicalTable, viewer.getTable());
 			this.viewer.setLabelProvider(labelprovider);
 			this.cols = labelprovider.getCols();
 			this.rows = labelprovider.getRows();
 			this.viewer.setInput(this.lexicalTable);
-			
+
 			// initial sorting
 			if (!update) {
-				this.sort(unitColumn, -2);
+				try {
+					this.sort(unitColumn, -2);
+				} catch (Exception e) {
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
 			}
 		}
-		
-		
+
+
 		this.viewer.getControl().setRedraw(true);
-		
-		
+
+
 		// Refresh and pack the columns
 		TXMEditor.packColumns(this.viewer);
-		
+
 		this.viewer.getTable().deselectAll();
 		this.viewer.getTable().setFocus();
-		
-		
+
+
 	}
-	
-	
+
+
 	/**
 	 * Sets the col comparator.
 	 *
@@ -612,7 +630,7 @@
 		 * currentComparator.initialize(cooc.getCorpus());
 		 */
 	}
-	
+
 	/**
 	 * Gets the corpus.
 	 *
@@ -621,9 +639,9 @@
 	public CQPCorpus getCorpus() {
 		return null;
 	}
-	
-	
-	
+
+
+
 	/**
 	 * Gets the line table viewer.
 	 *
@@ -632,7 +650,7 @@
 	public TableViewer getlineTableViewer() {
 		return viewer;
 	}
-	
+
 	/**
 	 * Gets the lexical table.
 	 *
@@ -641,7 +659,7 @@
 	public LexicalTable getLexicalTable() {
 		return lexicalTable;
 	}
-	
+
 	/**
 	 * Gets the cols.
 	 *
@@ -650,7 +668,7 @@
 	public List<double[]> getCols() {
 		return cols;
 	}
-	
+
 	/**
 	 * Export data.
 	 *
@@ -660,7 +678,7 @@
 	public void exportData(File file) {
 		lexicalTable.getData().toTxt(file, TXMPreferences.DEFAULT_ENCODING, "\t", ""); //$NON-NLS-1$ //$NON-NLS-2$
 	}
-	
+
 	/**
 	 * Import data.
 	 *
@@ -672,7 +690,7 @@
 			String encoding = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_ENCODING);
 			String colseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_COL_SEPARATOR);
 			String txtseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_TXT_SEPARATOR);
-			
+
 			if (lexicalTable.getData().importData(file, encoding, colseparator, txtseparator)) {
 				lexicalTable.setAltered();
 				// fix col names
@@ -704,25 +722,37 @@
 			org.txm.utils.logger.Log.printStackTrace(e);
 		}
 	}
-	
-	
-	
+
+
+
 	/**
 	 * Sort.
 	 *
 	 * @param col the col
 	 * @param index the index
+	 * @throws Exception 
+	 * @throws StatException 
 	 */
 	// FIXME: SJ: try to use a ViewerSorter instead of this but also manage the result sorting for export
-	public void sort(TableViewerColumn col, int index) {
-		
+	public void sort(TableViewerColumn col, int index) throws StatException, Exception {
+
+		List currentSelection = viewer.getStructuredSelection().toList();
+		HashSet<String> selectedEntries = new HashSet<String>();
+		String[] rowNames = this.getResult().getRowNames().asStringsArray();
+		for (Object o : currentSelection) {
+			int i = (int) o;
+			selectedEntries.add(rowNames[i]);
+		}
+		System.out.println("selection before sort: "+currentSelection);
+		System.out.println("selection entries before sort: "+selectedEntries);
+
 		if (index == previousSortedCol) {
 			reverse = !reverse;
 		}
 		else {
 			reverse = DEFAULTREVERSE;
 		}
-		
+
 		if (index == -3) {// rownames
 			lexicalTable.getData().sortRowNames(reverse);
 		}
@@ -738,49 +768,62 @@
 		else if (index >= 0) {
 			lexicalTable.getData().sort(index, reverse);
 		}
-		
+
+		rowNames = this.getResult().getRowNames().asStringsArray(); // get updated rowNames (new order)
+		List<Integer> newSelection = new ArrayList<Integer>();
+		if (selectedEntries.size() > 0) {
+			for (int i = 0 ; i < rowNames.length ; i++) {
+				if (selectedEntries.contains(rowNames[i])) {
+					newSelection.add(i);
+					System.out.println("found: "+rowNames[i]);
+				}
+			}
+		}
+
 		previousSortedCol = index;
-		
+
 		refreshTable(true);
-		
+
 		// viewer.getTable().setSortColumn(col.getColumn());
 		viewer.getTable().setSortColumn(viewer.getTable().getColumn(index + 4));
-		
+
 		if (reverse) {
 			viewer.getTable().setSortDirection(SWT.DOWN);
 		}
 		else {
 			viewer.getTable().setSortDirection(SWT.UP);
 		}
-		
+
 		// Refresh and pack the columns
 		TXMEditor.refreshColumns(this.viewer);
-		
+
+		viewer.setSelection(new StructuredSelection(newSelection));
+
 	}
-	
-	
+
+
 	@Override
 	public void updateEditorFromResult(boolean update) {
-		
+
 		// enable/disable the edition buttons according to the computed state
 		if (this.lexicalTable.getData() != null) {
 			this.mergeDeleteColumnsButton.setEnabled(true);
 			this.mergeDeleteRowsButton.setEnabled(true);
-			
+
 			this.refreshInfos();
 		}
 		else {
 			this.mergeDeleteColumnsButton.setEnabled(false);
 			this.mergeDeleteRowsButton.setEnabled(false);
 		}
-		
+
 		this.refreshTable(update);
-		
+
 		QueriesView.refresh();
 		RVariablesView.refresh();
 	}
-	
-	
+
+
 	@Override
 	public void updateResultFromEditor() {
 		// FIXME: SJ: needs to manage here the merge/deletion of rows and columns
