]> git.lyx.org Git - lyx.git/blob - src/insets/insettabular.C
Tell X the selection status also after it is changed by the keyboard, since
[lyx.git] / src / insets / insettabular.C
1 /**
2  * \file insettabular.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insettabular.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17 #include "BufferView.h"
18 #include "cursor.h"
19 #include "CutAndPaste.h"
20 #include "coordcache.h"
21 #include "debug.h"
22 #include "dispatchresult.h"
23 #include "funcrequest.h"
24 #include "FuncStatus.h"
25 #include "gettext.h"
26 #include "language.h"
27 #include "LColor.h"
28 #include "lyx_cb.h"
29 #include "lyxlex.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
32 #include "paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "undo.h"
36
37 #include "support/convert.h"
38
39 #include "frontends/Alert.h"
40 #include "frontends/Clipboard.h"
41 #include "frontends/Painter.h"
42 #include "frontends/Selection.h"
43
44 #include <sstream>
45 #include <iostream>
46 #include <limits>
47
48
49 namespace lyx {
50
51 using cap::dirtyTabularStack;
52 using cap::tabularStackDirty;
53
54 using graphics::PreviewLoader;
55
56 using support::ltrim;
57
58 using frontend::Painter;
59 using frontend::Clipboard;
60
61 using boost::shared_ptr;
62
63 using std::auto_ptr;
64 using std::endl;
65 using std::max;
66 using std::string;
67 using std::istringstream;
68 using std::ostream;
69 using std::ostringstream;
70 using std::swap;
71 using std::vector;
72
73 namespace Alert = frontend::Alert;
74
75
76 namespace {
77
78 int const ADD_TO_HEIGHT = 2;
79 int const ADD_TO_TABULAR_WIDTH = 2;
80 int const default_line_space = 10;
81
82 ///
83 boost::scoped_ptr<LyXTabular> paste_tabular;
84
85
86 struct TabularFeature {
87         LyXTabular::Feature action;
88         string feature;
89 };
90
91
92 TabularFeature tabularFeature[] =
93 {
94         { LyXTabular::APPEND_ROW, "append-row" },
95         { LyXTabular::APPEND_COLUMN, "append-column" },
96         { LyXTabular::DELETE_ROW, "delete-row" },
97         { LyXTabular::DELETE_COLUMN, "delete-column" },
98         { LyXTabular::COPY_ROW, "copy-row" },
99         { LyXTabular::COPY_COLUMN, "copy-column" },
100         { LyXTabular::TOGGLE_LINE_TOP, "toggle-line-top" },
101         { LyXTabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
102         { LyXTabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
103         { LyXTabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
104         { LyXTabular::ALIGN_LEFT, "align-left" },
105         { LyXTabular::ALIGN_RIGHT, "align-right" },
106         { LyXTabular::ALIGN_CENTER, "align-center" },
107         { LyXTabular::ALIGN_BLOCK, "align-block" },
108         { LyXTabular::VALIGN_TOP, "valign-top" },
109         { LyXTabular::VALIGN_BOTTOM, "valign-bottom" },
110         { LyXTabular::VALIGN_MIDDLE, "valign-middle" },
111         { LyXTabular::M_TOGGLE_LINE_TOP, "m-toggle-line-top" },
112         { LyXTabular::M_TOGGLE_LINE_BOTTOM, "m-toggle-line-bottom" },
113         { LyXTabular::M_TOGGLE_LINE_LEFT, "m-toggle-line-left" },
114         { LyXTabular::M_TOGGLE_LINE_RIGHT, "m-toggle-line-right" },
115         { LyXTabular::M_ALIGN_LEFT, "m-align-left" },
116         { LyXTabular::M_ALIGN_RIGHT, "m-align-right" },
117         { LyXTabular::M_ALIGN_CENTER, "m-align-center" },
118         { LyXTabular::M_VALIGN_TOP, "m-valign-top" },
119         { LyXTabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
120         { LyXTabular::M_VALIGN_MIDDLE, "m-valign-middle" },
121         { LyXTabular::MULTICOLUMN, "multicolumn" },
122         { LyXTabular::SET_ALL_LINES, "set-all-lines" },
123         { LyXTabular::UNSET_ALL_LINES, "unset-all-lines" },
124         { LyXTabular::SET_LONGTABULAR, "set-longtabular" },
125         { LyXTabular::UNSET_LONGTABULAR, "unset-longtabular" },
126         { LyXTabular::SET_PWIDTH, "set-pwidth" },
127         { LyXTabular::SET_MPWIDTH, "set-mpwidth" },
128         { LyXTabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
129         { LyXTabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
130         { LyXTabular::SET_ROTATE_CELL, "set-rotate-cell" },
131         { LyXTabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
132         { LyXTabular::SET_USEBOX, "set-usebox" },
133         { LyXTabular::SET_LTHEAD, "set-lthead" },
134         { LyXTabular::UNSET_LTHEAD, "unset-lthead" },
135         { LyXTabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
136         { LyXTabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
137         { LyXTabular::SET_LTFOOT, "set-ltfoot" },
138         { LyXTabular::UNSET_LTFOOT, "unset-ltfoot" },
139         { LyXTabular::SET_LTLASTFOOT, "set-ltlastfoot" },
140         { LyXTabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
141         { LyXTabular::SET_LTNEWPAGE, "set-ltnewpage" },
142         { LyXTabular::SET_SPECIAL_COLUMN, "set-special-column" },
143         { LyXTabular::SET_SPECIAL_MULTI, "set-special-multi" },
144         { LyXTabular::SET_BOOKTABS, "set-booktabs" },
145         { LyXTabular::UNSET_BOOKTABS, "unset-booktabs" },
146         { LyXTabular::SET_TOP_SPACE, "set-top-space" },
147         { LyXTabular::SET_BOTTOM_SPACE, "set-bottom-space" },
148         { LyXTabular::SET_INTERLINE_SPACE, "set-interline-space" },
149         { LyXTabular::LAST_ACTION, "" }
150 };
151
152
153 class FeatureEqual : public std::unary_function<TabularFeature, bool> {
154 public:
155         FeatureEqual(LyXTabular::Feature feature)
156                 : feature_(feature) {}
157         bool operator()(TabularFeature const & tf) const {
158                 return tf.action == feature_;
159         }
160 private:
161         LyXTabular::Feature feature_;
162 };
163
164 } // namespace anon
165
166
167 string const featureAsString(LyXTabular::Feature feature)
168 {
169         TabularFeature * end = tabularFeature +
170                 sizeof(tabularFeature) / sizeof(TabularFeature);
171         TabularFeature * it = std::find_if(tabularFeature, end,
172                                            FeatureEqual(feature));
173         return (it == end) ? string() : it->feature;
174 }
175
176
177 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
178                            col_type columns)
179         : tabular(buf.params(), max(rows, row_type(1)),
180           max(columns, col_type(1))), buffer_(&buf), scx_(0)
181 {}
182
183
184 InsetTabular::InsetTabular(InsetTabular const & tab)
185         : InsetOld(tab), tabular(tab.tabular),
186                 buffer_(tab.buffer_), scx_(0)
187 {}
188
189
190 InsetTabular::~InsetTabular()
191 {
192         InsetTabularMailer(*this).hideDialog();
193 }
194
195
196 auto_ptr<InsetBase> InsetTabular::doClone() const
197 {
198         return auto_ptr<InsetBase>(new InsetTabular(*this));
199 }
200
201
202 Buffer const & InsetTabular::buffer() const
203 {
204         return *buffer_;
205 }
206
207
208 void InsetTabular::buffer(Buffer const * b)
209 {
210         buffer_ = b;
211 }
212
213
214 void InsetTabular::write(Buffer const & buf, ostream & os) const
215 {
216         os << "Tabular" << endl;
217         tabular.write(buf, os);
218 }
219
220
221 void InsetTabular::read(Buffer const & buf, LyXLex & lex)
222 {
223         bool const old_format = (lex.getString() == "\\LyXTable");
224
225         tabular.read(buf, lex);
226
227         if (old_format)
228                 return;
229
230         lex.next();
231         string token = lex.getString();
232         while (lex.isOK() && (token != "\\end_inset")) {
233                 lex.next();
234                 token = lex.getString();
235         }
236         if (token != "\\end_inset") {
237                 lex.printError("Missing \\end_inset at this point. "
238                                "Read: `$$Token'");
239         }
240 }
241
242
243 bool InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
244 {
245         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
246         //      mi.base.textwidth << "\n";
247         if (!mi.base.bv) {
248                 lyxerr << "InsetTabular::metrics: need bv" << endl;
249                 BOOST_ASSERT(false);
250         }
251
252         row_type i = 0;
253         for (idx_type cell = 0; i < tabular.rows(); ++i) {
254                 int maxAsc = 0;
255                 int maxDesc = 0;
256                 for (col_type j = 0; j < tabular.columns(); ++j) {
257                         if (tabular.isPartOfMultiColumn(i, j))
258                                 // Multicolumn cell, but not first one
259                                 continue;
260                         Dimension dim;
261                         MetricsInfo m = mi;
262                         LyXLength p_width;
263                         if (tabular.cell_info[i][j].multicolumn ==
264                             LyXTabular::CELL_BEGIN_OF_MULTICOLUMN)
265                                 p_width = tabular.cellinfo_of_cell(cell).p_width;
266                         else
267                                 p_width = tabular.column_info[j].p_width;
268                         if (!p_width.zero())
269                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
270                         tabular.getCellInset(cell)->metrics(m, dim);
271                         if (!p_width.zero())
272                                 dim.wid = m.base.textwidth;
273                         tabular.setWidthOfCell(cell, dim.wid);
274                         if (p_width.zero()) {
275                                 m.base.textwidth = dim.wid + 2 * ADD_TO_TABULAR_WIDTH;
276                                 // FIXME there must be a way to get rid of
277                                 // the second metrics call
278                                 tabular.getCellInset(cell)->metrics(m, dim);
279                         }
280                         maxAsc  = max(maxAsc, dim.asc);
281                         maxDesc = max(maxDesc, dim.des);
282                         ++cell;
283                 }
284                 int const top_space = tabular.row_info[i].top_space_default ?
285                         default_line_space :
286                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
287                 tabular.setAscentOfRow(i, maxAsc + ADD_TO_HEIGHT + top_space);
288                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
289                         default_line_space :
290                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
291                 tabular.setDescentOfRow(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
292         }
293
294         dim.asc = tabular.getAscentOfRow(0);
295         dim.des = tabular.getHeightOfTabular() - dim.asc;
296         dim.wid = tabular.getWidthOfTabular() + 2 * ADD_TO_TABULAR_WIDTH;
297         bool const changed = dim_ != dim;
298         dim_ = dim;
299         return changed;
300 }
301
302
303 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
304 {
305         setPosCache(pi, x, y);
306
307         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
308         BufferView * bv = pi.base.bv;
309
310         resetPos(bv->cursor());
311
312         x += scx_;
313         x += ADD_TO_TABULAR_WIDTH;
314
315         idx_type idx = 0;
316         first_visible_cell = LyXTabular::npos;
317         for (row_type i = 0; i < tabular.rows(); ++i) {
318                 int nx = x;
319                 int const a = tabular.getAscentOfRow(i);
320                 int const d = tabular.getDescentOfRow(i);
321                 idx = tabular.getCellNumber(i, 0);
322                 for (col_type j = 0; j < tabular.columns(); ++j) {
323                         if (tabular.isPartOfMultiColumn(i, j))
324                                 continue;
325                         if (first_visible_cell == LyXTabular::npos)
326                                 first_visible_cell = idx;
327
328                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
329                         if (nx + tabular.getWidthOfColumn(idx) < 0
330                             || nx > bv->workWidth()
331                             || y + d < 0
332                             || y - a > bv->workHeight()) {
333                                 pi.pain.setDrawingEnabled(false);
334                                 cell(idx)->draw(pi, cx, y);
335                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
336                                 pi.pain.setDrawingEnabled(true);
337                         } else {
338                                 cell(idx)->draw(pi, cx, y);
339                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
340                         }
341                         nx += tabular.getWidthOfColumn(idx);
342                         ++idx;
343                 }
344
345                 if (i + 1 < tabular.rows())
346                         y += d + tabular.getAscentOfRow(i + 1) +
347                                 tabular.getAdditionalHeight(i + 1);
348         }
349 }
350
351
352 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
353 {
354         setPosCache(pi, x, y);
355
356         LCursor & cur = pi.base.bv->cursor();
357
358         x += scx_ + ADD_TO_TABULAR_WIDTH;
359
360         // Paint background of current tabular
361         int const w = tabular.getWidthOfTabular();
362         int const h = tabular.getHeightOfTabular();
363         int yy = y - tabular.getAscentOfRow(0);
364         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
365
366         if (!cur.selection())
367                 return;
368         if (!ptr_cmp(&cur.inset(), this))
369                 return;
370
371         //resetPos(cur);
372
373
374         if (tablemode(cur)) {
375                 row_type rs, re;
376                 col_type cs, ce;
377                 getSelection(cur, rs, re, cs, ce);
378                 y -= tabular.getAscentOfRow(0);
379                 for (row_type j = 0; j < tabular.rows(); ++j) {
380                         int const a = tabular.getAscentOfRow(j);
381                         int const h = a + tabular.getDescentOfRow(j);
382                         int xx = x;
383                         y += tabular.getAdditionalHeight(j);
384                         for (col_type i = 0; i < tabular.columns(); ++i) {
385                                 if (tabular.isPartOfMultiColumn(j, i))
386                                         continue;
387                                 idx_type const cell =
388                                         tabular.getCellNumber(j, i);
389                                 int const w = tabular.getWidthOfColumn(cell);
390                                 if (i >= cs && i <= ce && j >= rs && j <= re)
391                                         pi.pain.fillRectangle(xx, y, w, h,
392                                                               LColor::selection);
393                                 xx += w;
394
395                         }
396                         y += h;
397                 }
398
399         } else {
400                 cur.text()->drawSelection(pi, x + getCellXPos(cur.idx()) + tabular.getBeginningOfTextInCell(cur.idx()), 0 /*this value is ignored */);
401         }
402 }
403
404
405 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
406                                  row_type row, idx_type cell, bool erased) const
407 {
408         int x2 = x + tabular.getWidthOfColumn(cell);
409         bool on_off = false;
410         LColor::color col = LColor::tabularline;
411         LColor::color onoffcol = LColor::tabularonoffline;
412
413         if (erased) {
414                 col = LColor::strikeout;
415                 onoffcol = LColor::strikeout;
416         }
417
418         if (!tabular.topAlreadyDrawn(cell)) {
419                 on_off = !tabular.topLine(cell);
420                 pain.line(x, y - tabular.getAscentOfRow(row),
421                           x2, y -  tabular.getAscentOfRow(row),
422                           on_off ? onoffcol : col,
423                           on_off ? Painter::line_onoffdash : Painter::line_solid);
424         }
425         on_off = !tabular.bottomLine(cell);
426         pain.line(x, y + tabular.getDescentOfRow(row),
427                   x2, y + tabular.getDescentOfRow(row),
428                   on_off ? onoffcol : col,
429                   on_off ? Painter::line_onoffdash : Painter::line_solid);
430         if (!tabular.leftAlreadyDrawn(cell)) {
431                 on_off = !tabular.leftLine(cell);
432                 pain.line(x, y -  tabular.getAscentOfRow(row),
433                           x, y +  tabular.getDescentOfRow(row),
434                           on_off ? onoffcol : col,
435                           on_off ? Painter::line_onoffdash : Painter::line_solid);
436         }
437         on_off = !tabular.rightLine(cell);
438         pain.line(x2 - tabular.getAdditionalWidth(cell),
439                   y -  tabular.getAscentOfRow(row),
440                   x2 - tabular.getAdditionalWidth(cell),
441                   y +  tabular.getDescentOfRow(row),
442                   on_off ? onoffcol : col,
443                   on_off ? Painter::line_onoffdash : Painter::line_solid);
444 }
445
446
447 docstring const InsetTabular::editMessage() const
448 {
449         return _("Opened table");
450 }
451
452
453 void InsetTabular::edit(LCursor & cur, bool left)
454 {
455         //lyxerr << "InsetTabular::edit: " << this << endl;
456         finishUndo();
457         cur.selection() = false;
458         cur.push(*this);
459         if (left) {
460                 if (isRightToLeft(cur))
461                         cur.idx() = tabular.getLastCellInRow(0);
462                 else
463                         cur.idx() = 0;
464                 cur.pit() = 0;
465                 cur.pos() = 0;
466         } else {
467                 if (isRightToLeft(cur))
468                         cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1);
469                 else
470                         cur.idx() = tabular.getNumberOfCells() - 1;
471                 cur.pit() = 0;
472                 cur.pos() = cur.lastpos(); // FIXME crude guess
473         }
474         // FIXME: this accesses the position cache before it is initialized
475         //resetPos(cur);
476         //cur.bv().fitCursor();
477 }
478
479
480 void InsetTabular::doDispatch(LCursor & cur, FuncRequest & cmd)
481 {
482         lyxerr[Debug::DEBUG] << "# InsetTabular::doDispatch: cmd: " << cmd
483                              << "\n  cur:" << cur << endl;
484         CursorSlice sl = cur.top();
485         LCursor & bvcur = cur.bv().cursor();
486
487         switch (cmd.action) {
488
489         case LFUN_MOUSE_PRESS:
490                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
491
492                 if (cmd.button() == mouse_button::button1 
493                     || (cmd.button() == mouse_button::button3 
494                         && (&bvcur.selBegin().inset() != this || !tablemode(bvcur)))) {
495                         if (!bvcur.selection() && !cur.bv().mouseSetCursor(cur))
496                                 cur.noUpdate();
497                         cur.selection() = false;
498                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
499                         cur.bv().mouseSetCursor(cur);
500                         break;
501                 }
502
503                 if (cmd.button() == mouse_button::button2) {
504                         cmd = FuncRequest(LFUN_PRIMARY_SELECTION_PASTE, "paragraph");
505                         doDispatch(cur, cmd);
506                 }
507                 break;
508
509         case LFUN_MOUSE_MOTION:
510                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
511                 if (cmd.button() == mouse_button::button1) {
512                         // only accept motions to places not deeper nested than the real anchor
513                         if (bvcur.anchor_.hasPart(cur)) {
514                                 // only update if selection changes
515                                 if (bvcur.idx() == cur.idx() &&
516                                         !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
517                                         cur.noUpdate();
518                                 setCursorFromCoordinates(cur, cmd.x, cmd.y);
519                                 bvcur.setCursor(cur);
520                                 bvcur.selection() = true;
521                         } else
522                                 cur.undispatched();
523                 }
524                 break;
525
526         case LFUN_MOUSE_RELEASE:
527                 //lyxerr << "# InsetTabular::MouseRelease\n" << bvcur << endl;
528                 if (cmd.button() == mouse_button::button1) {
529                         if (bvcur.selection())
530                                 theSelection().haveSelection(true);
531                 } else if (cmd.button() == mouse_button::button3)
532                         InsetTabularMailer(*this).showDialog(&cur.bv());
533                 break;
534
535         case LFUN_CELL_BACKWARD:
536                 movePrevCell(cur);
537                 cur.selection() = false;
538                 break;
539
540         case LFUN_CELL_FORWARD:
541                 moveNextCell(cur);
542                 cur.selection() = false;
543                 break;
544
545         case LFUN_CHAR_FORWARD_SELECT:
546         case LFUN_CHAR_FORWARD:
547                 cell(cur.idx())->dispatch(cur, cmd);
548                 if (!cur.result().dispatched()) {
549                         isRightToLeft(cur) ? movePrevCell(cur) : moveNextCell(cur);
550                         if (cmd.action == LFUN_CHAR_FORWARD_SELECT)
551                                 theSelection().haveSelection(cur.selection());
552                         if (sl == cur.top())
553                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
554                         else
555                                 cur.dispatched();
556                 }
557                 break;
558
559         case LFUN_CHAR_BACKWARD_SELECT:
560         case LFUN_CHAR_BACKWARD:
561                 cell(cur.idx())->dispatch(cur, cmd);
562                 if (!cur.result().dispatched()) {
563                         isRightToLeft(cur) ? moveNextCell(cur) : movePrevCell(cur);
564                         if (cmd.action == LFUN_CHAR_BACKWARD_SELECT)
565                                 theSelection().haveSelection(cur.selection());
566                         if (sl == cur.top())
567                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
568                         else
569                                 cur.dispatched();
570                 }
571                 break;
572
573         case LFUN_DOWN_SELECT:
574         case LFUN_DOWN:
575                 cell(cur.idx())->dispatch(cur, cmd);
576                 cur.dispatched(); // override the cell's decision
577                 if (sl == cur.top())
578                         // if our LyXText didn't do anything to the cursor
579                         // then we try to put the cursor into the cell below
580                         // setting also the right targetX.
581                         if (tabular.row_of_cell(cur.idx()) != tabular.rows() - 1) {
582                                 cur.idx() = tabular.getCellBelow(cur.idx());
583                                 cur.pit() = 0;
584                                 TextMetrics const & tm =
585                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
586                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
587                                 if (cmd.action == LFUN_DOWN_SELECT)
588                                         theSelection().haveSelection(cur.selection());
589                         }
590                 if (sl == cur.top()) {
591                         // we trick it to go to the RIGHT after leaving the
592                         // tabular.
593                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
594                         cur.undispatched();
595                 }
596                 break;
597
598         case LFUN_UP_SELECT:
599         case LFUN_UP:
600                 cell(cur.idx())->dispatch(cur, cmd);
601                 cur.dispatched(); // override the cell's decision
602                 if (sl == cur.top())
603                         // if our LyXText didn't do anything to the cursor
604                         // then we try to put the cursor into the cell above
605                         // setting also the right targetX.
606                         if (tabular.row_of_cell(cur.idx()) != 0) {
607                                 cur.idx() = tabular.getCellAbove(cur.idx());
608                                 cur.pit() = cur.lastpit();
609                                 LyXText const * text = cell(cur.idx())->getText(0);
610                                 TextMetrics const & tm = cur.bv().textMetrics(text);
611                                 ParagraphMetrics const & pm =
612                                         tm.parMetrics(cur.lastpit());
613                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
614                                 if (cmd.action == LFUN_UP_SELECT)
615                                         theSelection().haveSelection(cur.selection());
616                         }
617                 if (sl == cur.top()) {
618                         cmd = FuncRequest(LFUN_FINISHED_UP);
619                         cur.undispatched();
620                 }
621                 break;
622
623 //      case LFUN_SCREEN_DOWN: {
624 //              //if (hasSelection())
625 //              //      cur.selection() = false;
626 //              col_type const col = tabular.column_of_cell(cur.idx());
627 //              int const t =   cur.bv().top_y() + cur.bv().height();
628 //              if (t < yo() + tabular.getHeightOfTabular()) {
629 //                      cur.bv().scrollDocView(t);
630 //                      cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
631 //              } else {
632 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
633 //              }
634 //              cur.par() = 0;
635 //              cur.pos() = 0;
636 //              break;
637 //      }
638 //
639 //      case LFUN_SCREEN_UP: {
640 //              //if (hasSelection())
641 //              //      cur.selection() = false;
642 //              col_type const col = tabular.column_of_cell(cur.idx());
643 //              int const t =   cur.bv().top_y() + cur.bv().height();
644 //              if (yo() < 0) {
645 //                      cur.bv().scrollDocView(t);
646 //                      if (yo() > 0)
647 //                              cur.idx() = col;
648 //                      else
649 //                              cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
650 //              } else {
651 //                      cur.idx() = col;
652 //              }
653 //              cur.par() = cur.lastpar();
654 //              cur.pos() = cur.lastpos();
655 //              break;
656 //      }
657
658         case LFUN_LAYOUT_TABULAR:
659                 InsetTabularMailer(*this).showDialog(&cur.bv());
660                 break;
661
662         case LFUN_INSET_DIALOG_UPDATE:
663                 InsetTabularMailer(*this).updateDialog(&cur.bv());
664                 break;
665
666         case LFUN_TABULAR_FEATURE:
667                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
668                         cur.undispatched();
669                 break;
670
671         // insert file functions
672         case LFUN_FILE_INSERT_ASCII_PARA:
673         case LFUN_FILE_INSERT_ASCII: {
674                 // FIXME UNICODE
675                 string const tmpstr = getContentsOfAsciiFile(&cur.bv(), to_utf8(cmd.argument()), false);
676                 // FIXME: We don't know the encoding of the file
677                 if (!tmpstr.empty() && !insertAsciiString(cur.bv(), from_utf8(tmpstr), false))
678                         cur.undispatched();
679                 break;
680         }
681
682         case LFUN_CUT:
683                 if (tablemode(cur)) {
684                         if (copySelection(cur)) {
685                                 recordUndoInset(cur, Undo::DELETE);
686                                 cutSelection(cur);
687                         }
688                 }
689                 else
690                         cell(cur.idx())->dispatch(cur, cmd);
691                 break;
692
693         case LFUN_CHAR_DELETE_BACKWARD:
694         case LFUN_CHAR_DELETE_FORWARD:
695                 if (tablemode(cur)) {
696                         recordUndoInset(cur, Undo::DELETE);
697                         cutSelection(cur);
698                 }
699                 else
700                         cell(cur.idx())->dispatch(cur, cmd);
701                 break;
702
703         case LFUN_COPY:
704                 if (!cur.selection())
705                         break;
706                 if (tablemode(cur)) {
707                         finishUndo();
708                         copySelection(cur);
709                 } else
710                         cell(cur.idx())->dispatch(cur, cmd);
711                 break;
712
713         case LFUN_CLIPBOARD_PASTE:
714         case LFUN_PRIMARY_SELECTION_PASTE: {
715                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
716                         theClipboard().get() :
717                         theSelection().get();
718                 if (clip.empty())
719                         break;
720                 // pass to InsertAsciiString, but
721                 // only if we have multi-cell content
722                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
723                         if (insertAsciiString(cur.bv(), clip, false)) {
724                                 // content has been replaced,
725                                 // so cursor might be invalid
726                                 cur.pos() = cur.lastpos();
727                                 bvcur.setCursor(cur);
728                                 break;
729                         }
730                 }
731                 // Let the cell handle normal text
732                 cell(cur.idx())->dispatch(cur, cmd);
733                 break;
734         }
735
736         case LFUN_PASTE:
737                 if (tabularStackDirty() && theClipboard().isInternal()) {
738                         recordUndoInset(cur, Undo::INSERT);
739                         pasteSelection(cur);
740                         break;
741                 }
742                 cell(cur.idx())->dispatch(cur, cmd);
743                 break;
744
745         case LFUN_FONT_EMPH:
746         case LFUN_FONT_BOLD:
747         case LFUN_FONT_ROMAN:
748         case LFUN_FONT_NOUN:
749         case LFUN_FONT_ITAL:
750         case LFUN_FONT_FRAK:
751         case LFUN_FONT_CODE:
752         case LFUN_FONT_SANS:
753         case LFUN_FONT_FREE_APPLY:
754         case LFUN_FONT_FREE_UPDATE:
755         case LFUN_FONT_SIZE:
756         case LFUN_FONT_UNDERLINE:
757         case LFUN_LANGUAGE:
758         case LFUN_WORD_CAPITALIZE:
759         case LFUN_WORD_UPCASE:
760         case LFUN_WORD_LOWCASE:
761         case LFUN_CHARS_TRANSPOSE:
762                 if (tablemode(cur)) {
763                         row_type rs, re;
764                         col_type cs, ce;
765                         getSelection(cur, rs, re, cs, ce);
766                         LCursor tmpcur = cur;
767                         for (row_type i = rs; i <= re; ++i) {
768                                 for (col_type j = cs; j <= ce; ++j) {
769                                         // cursor follows cell:
770                                         tmpcur.idx() = tabular.getCellNumber(i, j);
771                                         // select this cell only:
772                                         tmpcur.pit() = 0;
773                                         tmpcur.pos() = 0;
774                                         tmpcur.resetAnchor();
775                                         tmpcur.pit() = tmpcur.lastpit();
776                                         tmpcur.pos() = tmpcur.top().lastpos();
777                                         tmpcur.setCursor(tmpcur);
778                                         tmpcur.setSelection();
779                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
780                                 }
781                         }
782                         break;
783                 } else {
784                         cell(cur.idx())->dispatch(cur, cmd);
785                         break;
786                 }
787         default:
788                 // we try to handle this event in the insets dispatch function.
789                 cell(cur.idx())->dispatch(cur, cmd);
790                 break;
791         }
792
793         // FIXME: this accesses the position cache before it is initialized
794         //resetPos(cur);
795         InsetTabularMailer(*this).updateDialog(&cur.bv());
796 }
797
798
799 // function sets an object as defined in func_status.h:
800 // states OK, Unknown, Disabled, On, Off.
801 bool InsetTabular::getStatus(LCursor & cur, FuncRequest const & cmd,
802         FuncStatus & status) const
803 {
804         switch (cmd.action) {
805         case LFUN_TABULAR_FEATURE: {
806                 int action = LyXTabular::LAST_ACTION;
807                 int i = 0;
808                 for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
809                         string const tmp = tabularFeature[i].feature;
810                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
811                                 action = tabularFeature[i].action;
812                                 break;
813                         }
814                 }
815                 if (action == LyXTabular::LAST_ACTION) {
816                         status.clear();
817                         status.unknown(true);
818                         return true;
819                 }
820
821                 string const argument
822                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
823
824                 row_type sel_row_start = 0;
825                 row_type sel_row_end = 0;
826                 col_type dummy;
827                 LyXTabular::ltType dummyltt;
828                 bool flag = true;
829
830                 getSelection(cur, sel_row_start, sel_row_end, dummy, dummy);
831
832                 switch (action) {
833                 case LyXTabular::SET_PWIDTH:
834                 case LyXTabular::SET_MPWIDTH:
835                 case LyXTabular::SET_SPECIAL_COLUMN:
836                 case LyXTabular::SET_SPECIAL_MULTI:
837                 case LyXTabular::APPEND_ROW:
838                 case LyXTabular::APPEND_COLUMN:
839                 case LyXTabular::DELETE_ROW:
840                 case LyXTabular::DELETE_COLUMN:
841                 case LyXTabular::COPY_ROW:
842                 case LyXTabular::COPY_COLUMN:
843                 case LyXTabular::SET_ALL_LINES:
844                 case LyXTabular::UNSET_ALL_LINES:
845                 case LyXTabular::SET_TOP_SPACE:
846                 case LyXTabular::SET_BOTTOM_SPACE:
847                 case LyXTabular::SET_INTERLINE_SPACE:
848                         status.clear();
849                         return true;
850
851                 case LyXTabular::MULTICOLUMN:
852                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
853                         break;
854
855                 case LyXTabular::M_TOGGLE_LINE_TOP:
856                         flag = false;
857                 case LyXTabular::TOGGLE_LINE_TOP:
858                         status.setOnOff(tabular.topLine(cur.idx(), flag));
859                         break;
860
861                 case LyXTabular::M_TOGGLE_LINE_BOTTOM:
862                         flag = false;
863                 case LyXTabular::TOGGLE_LINE_BOTTOM:
864                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
865                         break;
866
867                 case LyXTabular::M_TOGGLE_LINE_LEFT:
868                         flag = false;
869                 case LyXTabular::TOGGLE_LINE_LEFT:
870                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
871                         break;
872
873                 case LyXTabular::M_TOGGLE_LINE_RIGHT:
874                         flag = false;
875                 case LyXTabular::TOGGLE_LINE_RIGHT:
876                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
877                         break;
878
879                 case LyXTabular::M_ALIGN_LEFT:
880                         flag = false;
881                 case LyXTabular::ALIGN_LEFT:
882                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
883                         break;
884
885                 case LyXTabular::M_ALIGN_RIGHT:
886                         flag = false;
887                 case LyXTabular::ALIGN_RIGHT:
888                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
889                         break;
890
891                 case LyXTabular::M_ALIGN_CENTER:
892                         flag = false;
893                 case LyXTabular::ALIGN_CENTER:
894                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
895                         break;
896
897                 case LyXTabular::ALIGN_BLOCK:
898                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
899                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
900                         break;
901
902                 case LyXTabular::M_VALIGN_TOP:
903                         flag = false;
904                 case LyXTabular::VALIGN_TOP:
905                         status.setOnOff(
906                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_TOP);
907                         break;
908
909                 case LyXTabular::M_VALIGN_BOTTOM:
910                         flag = false;
911                 case LyXTabular::VALIGN_BOTTOM:
912                         status.setOnOff(
913                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_BOTTOM);
914                         break;
915
916                 case LyXTabular::M_VALIGN_MIDDLE:
917                         flag = false;
918                 case LyXTabular::VALIGN_MIDDLE:
919                         status.setOnOff(
920                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_MIDDLE);
921                         break;
922
923                 case LyXTabular::SET_LONGTABULAR:
924                         status.setOnOff(tabular.isLongTabular());
925                         break;
926
927                 case LyXTabular::UNSET_LONGTABULAR:
928                         status.setOnOff(!tabular.isLongTabular());
929                         break;
930
931                 case LyXTabular::SET_ROTATE_TABULAR:
932                         status.setOnOff(tabular.getRotateTabular());
933                         break;
934
935                 case LyXTabular::UNSET_ROTATE_TABULAR:
936                         status.setOnOff(!tabular.getRotateTabular());
937                         break;
938
939                 case LyXTabular::SET_ROTATE_CELL:
940                         status.setOnOff(tabular.getRotateCell(cur.idx()));
941                         break;
942
943                 case LyXTabular::UNSET_ROTATE_CELL:
944                         status.setOnOff(!tabular.getRotateCell(cur.idx()));
945                         break;
946
947                 case LyXTabular::SET_USEBOX:
948                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
949                         break;
950
951                 case LyXTabular::SET_LTFIRSTHEAD:
952                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
953                         break;
954
955                 case LyXTabular::UNSET_LTFIRSTHEAD:
956                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
957                         break;
958
959                 case LyXTabular::SET_LTHEAD:
960                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
961                         break;
962
963                 case LyXTabular::UNSET_LTHEAD:
964                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
965                         break;
966
967                 case LyXTabular::SET_LTFOOT:
968                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
969                         break;
970
971                 case LyXTabular::UNSET_LTFOOT:
972                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
973                         break;
974
975                 case LyXTabular::SET_LTLASTFOOT:
976                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
977                         break;
978
979                 case LyXTabular::UNSET_LTLASTFOOT:
980                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
981                         break;
982
983                 case LyXTabular::SET_LTNEWPAGE:
984                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
985                         break;
986
987                 case LyXTabular::SET_BOOKTABS:
988                         status.setOnOff(tabular.useBookTabs());
989                         break;
990
991                 case LyXTabular::UNSET_BOOKTABS:
992                         status.setOnOff(!tabular.useBookTabs());
993                         break;
994
995                 default:
996                         status.clear();
997                         status.enabled(false);
998                         break;
999                 }
1000                 return true;
1001         }
1002
1003         // These are only enabled inside tabular
1004         case LFUN_CELL_BACKWARD:
1005         case LFUN_CELL_FORWARD:
1006                 status.enabled(true);
1007                 return true;
1008
1009         // disable these with multiple cells selected
1010         case LFUN_INSET_INSERT:
1011         case LFUN_TABULAR_INSERT:
1012         case LFUN_CHARSTYLE_INSERT:
1013         case LFUN_FLOAT_INSERT:
1014         case LFUN_FLOAT_WIDE_INSERT:
1015         case LFUN_FOOTNOTE_INSERT:
1016         case LFUN_MARGINALNOTE_INSERT:
1017         case LFUN_MATH_INSERT:
1018         case LFUN_MATH_MODE:
1019         case LFUN_MATH_MUTATE:
1020         case LFUN_MATH_DISPLAY:
1021         case LFUN_NOTE_INSERT:
1022         case LFUN_OPTIONAL_INSERT:
1023         case LFUN_BOX_INSERT:
1024         case LFUN_BRANCH_INSERT:
1025         case LFUN_WRAP_INSERT:
1026         case LFUN_ERT_INSERT: {
1027                 if (tablemode(cur)) {
1028                         status.enabled(false);
1029                         return true;
1030                 } else
1031                         return cell(cur.idx())->getStatus(cur, cmd, status);
1032         }
1033
1034         // disable in non-fixed-width cells
1035         case LFUN_BREAK_LINE:
1036         case LFUN_BREAK_PARAGRAPH:
1037         case LFUN_BREAK_PARAGRAPH_KEEP_LAYOUT:
1038         case LFUN_BREAK_PARAGRAPH_SKIP: {
1039                 if (tabular.getPWidth(cur.idx()).zero()) {
1040                         status.enabled(false);
1041                         return true;
1042                 } else
1043                         return cell(cur.idx())->getStatus(cur, cmd, status);
1044         }
1045
1046         case LFUN_PASTE:
1047                 if (tabularStackDirty() && theClipboard().isInternal()) {
1048                         status.enabled(true);
1049                         return true;
1050                 } else
1051                         return cell(cur.idx())->getStatus(cur, cmd, status);
1052
1053         case LFUN_INSET_MODIFY:
1054                 if (translate(cmd.getArg(0)) == TABULAR_CODE) {
1055                         status.enabled(true);
1056                         return true;
1057                 }
1058                 // Fall through
1059
1060         default:
1061                 // we try to handle this event in the insets dispatch function.
1062                 return cell(cur.idx())->getStatus(cur, cmd, status);
1063         }
1064 }
1065
1066
1067 int InsetTabular::latex(Buffer const & buf, odocstream & os,
1068                         OutputParams const & runparams) const
1069 {
1070         return tabular.latex(buf, os, runparams);
1071 }
1072
1073
1074 int InsetTabular::plaintext(Buffer const & buf, odocstream & os,
1075                         OutputParams const & runparams) const
1076 {
1077         int const dp = runparams.linelen ? runparams.depth : 0;
1078         return tabular.plaintext(buf, os, runparams, dp, false, 0);
1079 }
1080
1081
1082 int InsetTabular::docbook(Buffer const & buf, odocstream & os,
1083                           OutputParams const & runparams) const
1084 {
1085         int ret = 0;
1086         InsetBase * master = 0;
1087
1088 #ifdef WITH_WARNINGS
1089 #warning Why not pass a proper DocIterator here?
1090 #endif
1091 #if 0
1092         // if the table is inside a float it doesn't need the informaltable
1093         // wrapper. Search for it.
1094         for (master = owner(); master; master = master->owner())
1095                 if (master->lyxCode() == InsetBase::FLOAT_CODE)
1096                         break;
1097 #endif
1098
1099         if (!master) {
1100                 os << "<informaltable>";
1101                 ++ret;
1102         }
1103         ret += tabular.docbook(buf, os, runparams);
1104         if (!master) {
1105                 os << "</informaltable>";
1106                 ++ret;
1107         }
1108         return ret;
1109 }
1110
1111
1112 void InsetTabular::validate(LaTeXFeatures & features) const
1113 {
1114         tabular.validate(features);
1115 }
1116
1117
1118 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
1119 {
1120         return tabular.getCellInset(idx);
1121 }
1122
1123
1124 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
1125 {
1126         return tabular.getCellInset(idx);
1127 }
1128
1129
1130 void InsetTabular::cursorPos(BufferView const & bv,
1131                 CursorSlice const & sl, bool boundary, int & x, int & y) const
1132 {
1133         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
1134
1135         // y offset     correction
1136         int const row = tabular.row_of_cell(sl.idx());
1137         for (int i = 0; i <= row; ++i) {
1138                 if (i != 0) {
1139                         y += tabular.getAscentOfRow(i);
1140                         y += tabular.getAdditionalHeight(i);
1141                 }
1142                 if (i != row)
1143                         y += tabular.getDescentOfRow(i);
1144         }
1145
1146         // x offset correction
1147         int const col = tabular.column_of_cell(sl.idx());
1148         int idx = tabular.getCellNumber(row, 0);
1149         for (int j = 0; j < col; ++j) {
1150                 if (tabular.isPartOfMultiColumn(row, j))
1151                         continue;
1152                 x += tabular.getWidthOfColumn(idx);
1153                 ++idx;
1154         }
1155         x += tabular.getBeginningOfTextInCell(idx);
1156         x += ADD_TO_TABULAR_WIDTH;
1157         x += scx_;
1158 }
1159
1160
1161 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
1162 {
1163         int xx = 0;
1164         int yy = 0;
1165         InsetBase const & inset = *tabular.getCellInset(cell);
1166         Point o = bv.coordCache().getInsets().xy(&inset);
1167         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
1168         int const xend = xbeg + tabular.getWidthOfColumn(cell);
1169         row_type const row = tabular.row_of_cell(cell);
1170         int const ybeg = o.y_ - tabular.getAscentOfRow(row) -
1171                          tabular.getAdditionalHeight(row);
1172         int const yend = o.y_ + tabular.getDescentOfRow(row);
1173
1174         if (x < xbeg)
1175                 xx = xbeg - x;
1176         else if (x > xend)
1177                 xx = x - xend;
1178
1179         if (y < ybeg)
1180                 yy = ybeg - y;
1181         else if (y > yend)
1182                 yy = y - yend;
1183
1184         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
1185         //       << " ybeg=" << ybeg << " yend=" << yend
1186         //       << " xx=" << xx << " yy=" << yy
1187         //       << " dist=" << xx + yy << endl;
1188         return xx + yy;
1189 }
1190
1191
1192 InsetBase * InsetTabular::editXY(LCursor & cur, int x, int y)
1193 {
1194         //lyxerr << "InsetTabular::editXY: " << this << endl;
1195         cur.selection() = false;
1196         cur.push(*this);
1197         cur.idx() = getNearestCell(cur.bv(), x, y);
1198         resetPos(cur);
1199         return cell(cur.idx())->text_.editXY(cur, x, y);
1200 }
1201
1202
1203 void InsetTabular::setCursorFromCoordinates(LCursor & cur, int x, int y) const
1204 {
1205         cur.idx() = getNearestCell(cur.bv(), x, y);
1206         cell(cur.idx())->text_.setCursorFromCoordinates(cur, x, y);
1207 }
1208
1209
1210 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
1211 {
1212         idx_type idx_min = 0;
1213         int dist_min = std::numeric_limits<int>::max();
1214         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1215                 if (bv.coordCache().getInsets().has(tabular.getCellInset(i).get())) {
1216                         int const d = dist(bv, i, x, y);
1217                         if (d < dist_min) {
1218                                 dist_min = d;
1219                                 idx_min = i;
1220                         }
1221                 }
1222         }
1223         return idx_min;
1224 }
1225
1226
1227 int InsetTabular::getCellXPos(idx_type const cell) const
1228 {
1229         idx_type c = cell;
1230
1231         for (; !tabular.isFirstCellInRow(c); --c)
1232                 ;
1233         int lx = tabular.getWidthOfColumn(cell);
1234         for (; c < cell; ++c)
1235                 lx += tabular.getWidthOfColumn(c);
1236
1237         return lx - tabular.getWidthOfColumn(cell);
1238 }
1239
1240
1241 void InsetTabular::resetPos(LCursor & cur) const
1242 {
1243         BufferView & bv = cur.bv();
1244         int const maxwidth = bv.workWidth();
1245
1246         if (&cur.inset() != this) {
1247                 scx_ = 0;
1248         } else {
1249                 int const X1 = 0;
1250                 int const X2 = maxwidth;
1251                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
1252                 int const x1 = xo(cur.bv()) + getCellXPos(cur.idx()) + offset;
1253                 int const x2 = x1 + tabular.getWidthOfColumn(cur.idx());
1254
1255                 if (x1 < X1)
1256                         scx_ = X1 + 20 - x1;
1257                 else if (x2 > X2)
1258                         scx_ = X2 - 20 - x2;
1259                 else
1260                         scx_ = 0;
1261         }
1262
1263         cur.updateFlags(Update::Force | Update::FitCursor);
1264
1265         InsetTabularMailer(*this).updateDialog(&bv);
1266 }
1267
1268
1269 void InsetTabular::moveNextCell(LCursor & cur)
1270 {
1271         if (isRightToLeft(cur)) {
1272                 if (tabular.isFirstCellInRow(cur.idx())) {
1273                         row_type const row = tabular.row_of_cell(cur.idx());
1274                         if (row == tabular.rows() - 1)
1275                                 return;
1276                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
1277                 } else {
1278                         if (cur.idx() == 0)
1279                                 return;
1280                         --cur.idx();
1281                 }
1282         } else {
1283                 if (tabular.isLastCell(cur.idx()))
1284                         return;
1285                 ++cur.idx();
1286         }
1287         cur.pit() = 0;
1288         cur.pos() = 0;
1289         resetPos(cur);
1290 }
1291
1292
1293 void InsetTabular::movePrevCell(LCursor & cur)
1294 {
1295         if (isRightToLeft(cur)) {
1296                 if (tabular.isLastCellInRow(cur.idx())) {
1297                         row_type const row = tabular.row_of_cell(cur.idx());
1298                         if (row == 0)
1299                                 return;
1300                         cur.idx() = tabular.getFirstCellInRow(row);
1301                         cur.idx() = tabular.getCellAbove(cur.idx());
1302                 } else {
1303                         if (tabular.isLastCell(cur.idx()))
1304                                 return;
1305                         ++cur.idx();
1306                 }
1307         } else {
1308                 if (cur.idx() == 0) // first cell
1309                         return;
1310                 --cur.idx();
1311         }
1312         cur.pit() = cur.lastpit();
1313         cur.pos() = cur.lastpos();
1314
1315         // FIXME: this accesses the position cache before it is initialized
1316         //resetPos(cur);
1317 }
1318
1319
1320 bool InsetTabular::tabularFeatures(LCursor & cur, string const & what)
1321 {
1322         LyXTabular::Feature action = LyXTabular::LAST_ACTION;
1323
1324         int i = 0;
1325         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
1326                 string const tmp = tabularFeature[i].feature;
1327
1328                 if (tmp == what.substr(0, tmp.length())) {
1329                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
1330                         //tabularFeatures[i].feature.length())) {
1331                         action = tabularFeature[i].action;
1332                         break;
1333                 }
1334         }
1335         if (action == LyXTabular::LAST_ACTION)
1336                 return false;
1337
1338         string const val =
1339                 ltrim(what.substr(tabularFeature[i].feature.length()));
1340         tabularFeatures(cur, action, val);
1341         return true;
1342 }
1343
1344
1345 namespace {
1346
1347 void checkLongtableSpecial(LyXTabular::ltType & ltt,
1348                           string const & special, bool & flag)
1349 {
1350         if (special == "dl_above") {
1351                 ltt.topDL = flag;
1352                 ltt.set = false;
1353         } else if (special == "dl_below") {
1354                 ltt.bottomDL = flag;
1355                 ltt.set = false;
1356         } else if (special == "empty") {
1357                 ltt.empty = flag;
1358                 ltt.set = false;
1359         } else if (flag) {
1360                 ltt.empty = false;
1361                 ltt.set = true;
1362         }
1363 }
1364
1365 } // anon namespace
1366
1367
1368 void InsetTabular::tabularFeatures(LCursor & cur,
1369         LyXTabular::Feature feature, string const & value)
1370 {
1371         BufferView & bv = cur.bv();
1372         col_type sel_col_start;
1373         col_type sel_col_end;
1374         row_type sel_row_start;
1375         row_type sel_row_end;
1376         bool setLines = false;
1377         LyXAlignment setAlign = LYX_ALIGN_LEFT;
1378         LyXTabular::VAlignment setVAlign = LyXTabular::LYX_VALIGN_TOP;
1379
1380         switch (feature) {
1381
1382         case LyXTabular::M_ALIGN_LEFT:
1383         case LyXTabular::ALIGN_LEFT:
1384                 setAlign = LYX_ALIGN_LEFT;
1385                 break;
1386
1387         case LyXTabular::M_ALIGN_RIGHT:
1388         case LyXTabular::ALIGN_RIGHT:
1389                 setAlign = LYX_ALIGN_RIGHT;
1390                 break;
1391
1392         case LyXTabular::M_ALIGN_CENTER:
1393         case LyXTabular::ALIGN_CENTER:
1394                 setAlign = LYX_ALIGN_CENTER;
1395                 break;
1396
1397         case LyXTabular::ALIGN_BLOCK:
1398                 setAlign = LYX_ALIGN_BLOCK;
1399                 break;
1400
1401         case LyXTabular::M_VALIGN_TOP:
1402         case LyXTabular::VALIGN_TOP:
1403                 setVAlign = LyXTabular::LYX_VALIGN_TOP;
1404                 break;
1405
1406         case LyXTabular::M_VALIGN_BOTTOM:
1407         case LyXTabular::VALIGN_BOTTOM:
1408                 setVAlign = LyXTabular::LYX_VALIGN_BOTTOM;
1409                 break;
1410
1411         case LyXTabular::M_VALIGN_MIDDLE:
1412         case LyXTabular::VALIGN_MIDDLE:
1413                 setVAlign = LyXTabular::LYX_VALIGN_MIDDLE;
1414                 break;
1415
1416         default:
1417                 break;
1418         }
1419
1420         recordUndoInset(cur, Undo::ATOMIC);
1421
1422         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1423         row_type const row = tabular.row_of_cell(cur.idx());
1424         col_type const column = tabular.column_of_cell(cur.idx());
1425         bool flag = true;
1426         LyXTabular::ltType ltt;
1427
1428         switch (feature) {
1429
1430         case LyXTabular::SET_PWIDTH: {
1431                 LyXLength const len(value);
1432                 tabular.setColumnPWidth(cur, cur.idx(), len);
1433                 if (len.zero()
1434                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
1435                         tabularFeatures(cur, LyXTabular::ALIGN_CENTER, string());
1436                 break;
1437         }
1438
1439         case LyXTabular::SET_MPWIDTH:
1440                 tabular.setMColumnPWidth(cur, cur.idx(), LyXLength(value));
1441                 break;
1442
1443         case LyXTabular::SET_SPECIAL_COLUMN:
1444         case LyXTabular::SET_SPECIAL_MULTI:
1445                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
1446                 break;
1447
1448         case LyXTabular::APPEND_ROW:
1449                 // append the row into the tabular
1450                 tabular.appendRow(bv.buffer()->params(), cur.idx());
1451                 break;
1452
1453         case LyXTabular::APPEND_COLUMN:
1454                 // append the column into the tabular
1455                 tabular.appendColumn(bv.buffer()->params(), cur.idx());
1456                 cur.idx() = tabular.getCellNumber(row, column);
1457                 break;
1458
1459         case LyXTabular::DELETE_ROW:
1460                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1461                         tabular.deleteRow(sel_row_start);
1462                 if (sel_row_start >= tabular.rows())
1463                         --sel_row_start;
1464                 cur.idx() = tabular.getCellNumber(sel_row_start, column);
1465                 cur.pit() = 0;
1466                 cur.pos() = 0;
1467                 cur.selection() = false;
1468                 break;
1469
1470         case LyXTabular::DELETE_COLUMN:
1471                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
1472                         tabular.deleteColumn(sel_col_start);
1473                 if (sel_col_start >= tabular.columns())
1474                         --sel_col_start;
1475                 cur.idx() = tabular.getCellNumber(row, sel_col_start);
1476                 cur.pit() = 0;
1477                 cur.pos() = 0;
1478                 cur.selection() = false;
1479                 break;
1480
1481         case LyXTabular::COPY_ROW:
1482                 tabular.copyRow(bv.buffer()->params(), row);
1483                 break;
1484
1485         case LyXTabular::COPY_COLUMN:
1486                 tabular.copyColumn(bv.buffer()->params(), column);
1487                 cur.idx() = tabular.getCellNumber(row, column);
1488                 break;
1489
1490         case LyXTabular::M_TOGGLE_LINE_TOP:
1491                 flag = false;
1492         case LyXTabular::TOGGLE_LINE_TOP: {
1493                 bool lineSet = !tabular.topLine(cur.idx(), flag);
1494                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1495                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1496                                 tabular.setTopLine(
1497                                         tabular.getCellNumber(i, j),
1498                                         lineSet, flag);
1499                 break;
1500         }
1501
1502         case LyXTabular::M_TOGGLE_LINE_BOTTOM:
1503                 flag = false;
1504         case LyXTabular::TOGGLE_LINE_BOTTOM: {
1505                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
1506                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1507                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1508                                 tabular.setBottomLine(
1509                                         tabular.getCellNumber(i, j),
1510                                         lineSet,
1511                                         flag);
1512                 break;
1513         }
1514
1515         case LyXTabular::M_TOGGLE_LINE_LEFT:
1516                 flag = false;
1517         case LyXTabular::TOGGLE_LINE_LEFT: {
1518                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
1519                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1520                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1521                                 tabular.setLeftLine(
1522                                         tabular.getCellNumber(i,j),
1523                                         lineSet,
1524                                         flag);
1525                 break;
1526         }
1527
1528         case LyXTabular::M_TOGGLE_LINE_RIGHT:
1529                 flag = false;
1530         case LyXTabular::TOGGLE_LINE_RIGHT: {
1531                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
1532                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1533                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1534                                 tabular.setRightLine(
1535                                         tabular.getCellNumber(i,j),
1536                                         lineSet,
1537                                         flag);
1538                 break;
1539         }
1540
1541         case LyXTabular::M_ALIGN_LEFT:
1542         case LyXTabular::M_ALIGN_RIGHT:
1543         case LyXTabular::M_ALIGN_CENTER:
1544                 flag = false;
1545         case LyXTabular::ALIGN_LEFT:
1546         case LyXTabular::ALIGN_RIGHT:
1547         case LyXTabular::ALIGN_CENTER:
1548         case LyXTabular::ALIGN_BLOCK:
1549                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1550                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1551                                 tabular.setAlignment(
1552                                         tabular.getCellNumber(i, j),
1553                                         setAlign,
1554                                         flag);
1555                 break;
1556
1557         case LyXTabular::M_VALIGN_TOP:
1558         case LyXTabular::M_VALIGN_BOTTOM:
1559         case LyXTabular::M_VALIGN_MIDDLE:
1560                 flag = false;
1561         case LyXTabular::VALIGN_TOP:
1562         case LyXTabular::VALIGN_BOTTOM:
1563         case LyXTabular::VALIGN_MIDDLE:
1564                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1565                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1566                                 tabular.setVAlignment(
1567                                         tabular.getCellNumber(i, j),
1568                                         setVAlign, flag);
1569                 break;
1570
1571         case LyXTabular::MULTICOLUMN: {
1572                 if (sel_row_start != sel_row_end) {
1573 #ifdef WITH_WARNINGS
1574 #warning Need I say it ? This is horrible.
1575 #endif
1576                         // FIXME UNICODE
1577                         Alert::error(_("Error setting multicolumn"),
1578                                      _("You cannot set multicolumn vertically."));
1579                         return;
1580                 }
1581                 if (!cur.selection()) {
1582                         // just multicol for one single cell
1583                         // check whether we are completely in a multicol
1584                         if (tabular.isMultiColumn(cur.idx()))
1585                                 tabular.unsetMultiColumn(cur.idx());
1586                         else
1587                                 tabular.setMultiColumn(bv.buffer(), cur.idx(), 1);
1588                         break;
1589                 }
1590                 // we have a selection so this means we just add all this
1591                 // cells to form a multicolumn cell
1592                 idx_type const s_start = cur.selBegin().idx();
1593                 idx_type const s_end = cur.selEnd().idx();
1594                 tabular.setMultiColumn(bv.buffer(), s_start, s_end - s_start + 1);
1595                 cur.idx() = s_start;
1596                 cur.pit() = 0;
1597                 cur.pos() = 0;
1598                 cur.selection() = false;
1599                 break;
1600         }
1601
1602         case LyXTabular::SET_ALL_LINES:
1603                 setLines = true;
1604         case LyXTabular::UNSET_ALL_LINES:
1605                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1606                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1607                                 tabular.setAllLines(
1608                                         tabular.getCellNumber(i,j), setLines);
1609                 break;
1610
1611         case LyXTabular::SET_LONGTABULAR:
1612                 tabular.setLongTabular(true);
1613                 break;
1614
1615         case LyXTabular::UNSET_LONGTABULAR:
1616                 tabular.setLongTabular(false);
1617                 break;
1618
1619         case LyXTabular::SET_ROTATE_TABULAR:
1620                 tabular.setRotateTabular(true);
1621                 break;
1622
1623         case LyXTabular::UNSET_ROTATE_TABULAR:
1624                 tabular.setRotateTabular(false);
1625                 break;
1626
1627         case LyXTabular::SET_ROTATE_CELL:
1628                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1629                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1630                                 tabular.setRotateCell(
1631                                         tabular.getCellNumber(i, j), true);
1632                 break;
1633
1634         case LyXTabular::UNSET_ROTATE_CELL:
1635                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1636                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1637                                 tabular.setRotateCell(
1638                                         tabular.getCellNumber(i, j), false);
1639                 break;
1640
1641         case LyXTabular::SET_USEBOX: {
1642                 LyXTabular::BoxType val = LyXTabular::BoxType(convert<int>(value));
1643                 if (val == tabular.getUsebox(cur.idx()))
1644                         val = LyXTabular::BOX_NONE;
1645                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1646                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1647                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1648                 break;
1649         }
1650
1651         case LyXTabular::UNSET_LTFIRSTHEAD:
1652                 flag = false;
1653         case LyXTabular::SET_LTFIRSTHEAD:
1654                 tabular.getRowOfLTFirstHead(row, ltt);
1655                 checkLongtableSpecial(ltt, value, flag);
1656                 tabular.setLTHead(row, flag, ltt, true);
1657                 break;
1658
1659         case LyXTabular::UNSET_LTHEAD:
1660                 flag = false;
1661         case LyXTabular::SET_LTHEAD:
1662                 tabular.getRowOfLTHead(row, ltt);
1663                 checkLongtableSpecial(ltt, value, flag);
1664                 tabular.setLTHead(row, flag, ltt, false);
1665                 break;
1666
1667         case LyXTabular::UNSET_LTFOOT:
1668                 flag = false;
1669         case LyXTabular::SET_LTFOOT:
1670                 tabular.getRowOfLTFoot(row, ltt);
1671                 checkLongtableSpecial(ltt, value, flag);
1672                 tabular.setLTFoot(row, flag, ltt, false);
1673                 break;
1674
1675         case LyXTabular::UNSET_LTLASTFOOT:
1676                 flag = false;
1677         case LyXTabular::SET_LTLASTFOOT:
1678                 tabular.getRowOfLTLastFoot(row, ltt);
1679                 checkLongtableSpecial(ltt, value, flag);
1680                 tabular.setLTFoot(row, flag, ltt, true);
1681                 break;
1682
1683         case LyXTabular::SET_LTNEWPAGE:
1684                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1685                 break;
1686
1687         case LyXTabular::SET_BOOKTABS:
1688                 tabular.setBookTabs(true);
1689                 break;
1690
1691         case LyXTabular::UNSET_BOOKTABS:
1692                 tabular.setBookTabs(false);
1693                 break;
1694
1695         case LyXTabular::SET_TOP_SPACE: {
1696                 LyXLength len;
1697                 if (value == "default")
1698                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1699                                 tabular.row_info[i].top_space_default = true;
1700                 else if (isValidLength(value, &len))
1701                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1702                                 tabular.row_info[i].top_space_default = false;
1703                                 tabular.row_info[i].top_space = len;
1704                         }
1705                 else
1706                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1707                                 tabular.row_info[i].top_space_default = false;
1708                                 tabular.row_info[i].top_space = len;
1709                         }
1710                 break;
1711         }
1712
1713         case LyXTabular::SET_BOTTOM_SPACE: {
1714                 LyXLength len;
1715                 if (value == "default")
1716                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1717                                 tabular.row_info[i].bottom_space_default = true;
1718                 else if (isValidLength(value, &len))
1719                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1720                                 tabular.row_info[i].bottom_space_default = false;
1721                                 tabular.row_info[i].bottom_space = len;
1722                         }
1723                 else
1724                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1725                                 tabular.row_info[i].bottom_space_default = false;
1726                                 tabular.row_info[i].bottom_space = len;
1727                         }
1728                 break;
1729         }
1730
1731         case LyXTabular::SET_INTERLINE_SPACE: {
1732                 LyXLength len;
1733                 if (value == "default")
1734                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1735                                 tabular.row_info[i].interline_space_default = true;
1736                 else if (isValidLength(value, &len))
1737                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1738                                 tabular.row_info[i].interline_space_default = false;
1739                                 tabular.row_info[i].interline_space = len;
1740                         }
1741                 else
1742                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1743                                 tabular.row_info[i].interline_space_default = false;
1744                                 tabular.row_info[i].interline_space = len;
1745                         }
1746                 break;
1747         }
1748
1749         // dummy stuff just to avoid warnings
1750         case LyXTabular::LAST_ACTION:
1751                 break;
1752         }
1753
1754         InsetTabularMailer(*this).updateDialog(&bv);
1755 }
1756
1757
1758 bool InsetTabular::showInsetDialog(BufferView * bv) const
1759 {
1760         InsetTabularMailer(*this).showDialog(bv);
1761         return true;
1762 }
1763
1764
1765 void InsetTabular::openLayoutDialog(BufferView * bv) const
1766 {
1767         InsetTabularMailer(*this).showDialog(bv);
1768 }
1769
1770
1771 bool InsetTabular::copySelection(LCursor & cur)
1772 {
1773         if (!cur.selection())
1774                 return false;
1775
1776         row_type rs, re;
1777         col_type cs, ce;
1778         getSelection(cur, rs, re, cs, ce);
1779
1780         paste_tabular.reset(new LyXTabular(tabular));
1781
1782         for (row_type i = 0; i < rs; ++i)
1783                 paste_tabular->deleteRow(0);
1784
1785         row_type const rows = re - rs + 1;
1786         while (paste_tabular->rows() > rows)
1787                 paste_tabular->deleteRow(rows);
1788
1789         paste_tabular->setTopLine(0, true, true);
1790         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
1791                                      true, true);
1792
1793         for (col_type i = 0; i < cs; ++i)
1794                 paste_tabular->deleteColumn(0);
1795
1796         col_type const columns = ce - cs + 1;
1797         while (paste_tabular->columns() > columns)
1798                 paste_tabular->deleteColumn(columns);
1799
1800         paste_tabular->setLeftLine(0, true, true);
1801         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
1802                                     true, true);
1803
1804         odocstringstream os;
1805         OutputParams const runparams;
1806         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
1807         theClipboard().put(os.str());
1808         // mark tabular stack dirty
1809         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
1810         // when we (hopefully) have a one-for-all paste mechanism.
1811         dirtyTabularStack(true);
1812
1813         return true;
1814 }
1815
1816
1817 bool InsetTabular::pasteSelection(LCursor & cur)
1818 {
1819         if (!paste_tabular)
1820                 return false;
1821         col_type const actcol = tabular.column_of_cell(cur.idx());
1822         row_type const actrow = tabular.row_of_cell(cur.idx());
1823         for (row_type r1 = 0, r2 = actrow;
1824              r1 < paste_tabular->rows() && r2 < tabular.rows();
1825              ++r1, ++r2) {
1826                 for (col_type c1 = 0, c2 = actcol;
1827                     c1 < paste_tabular->columns() && c2 < tabular.columns();
1828                     ++c1, ++c2) {
1829                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
1830                             tabular.isPartOfMultiColumn(r2, c2))
1831                                 continue;
1832                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
1833                                 --c2;
1834                                 continue;
1835                         }
1836                         if (tabular.isPartOfMultiColumn(r2, c2)) {
1837                                 --c1;
1838                                 continue;
1839                         }
1840                         shared_ptr<InsetText> inset(
1841                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
1842                         tabular.setCellInset(r2, c2, inset);
1843                         // FIXME: change tracking (MG)
1844                         inset->setChange(Change(cur.buffer().params().trackChanges ?
1845                                                 Change::INSERTED : Change::UNCHANGED));
1846                         cur.pos() = 0;
1847                 }
1848         }
1849         return true;
1850 }
1851
1852
1853 void InsetTabular::cutSelection(LCursor & cur)
1854 {
1855         if (!cur.selection())
1856                 return;
1857
1858         row_type rs, re;
1859         col_type cs, ce;
1860         getSelection(cur, rs, re, cs, ce);
1861         for (row_type i = rs; i <= re; ++i) {
1862                 for (col_type j = cs; j <= ce; ++j) {
1863                         shared_ptr<InsetText> t
1864                                 = cell(tabular.getCellNumber(i, j));
1865                         if (cur.buffer().params().trackChanges)
1866                                 // FIXME: Change tracking (MG)
1867                                 t->setChange(Change(Change::DELETED));
1868                         else
1869                                 t->clear();
1870                 }
1871         }
1872
1873         // cursor position might be invalid now
1874         if (cur.pit() > cur.lastpit())
1875                 cur.pit() = cur.lastpit();
1876         if (cur.pos() > cur.lastpos())
1877                 cur.pos() = cur.lastpos();
1878         cur.clearSelection();
1879         theSelection().haveSelection(false);
1880 }
1881
1882
1883 bool InsetTabular::isRightToLeft(LCursor & cur) const
1884 {
1885         BOOST_ASSERT(cur.depth() > 1);
1886         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
1887         pos_type const parentpos = cur[cur.depth() - 2].pos();
1888         return parentpar.getFontSettings(cur.bv().buffer()->params(),
1889                                          parentpos).language()->rightToLeft();
1890 }
1891
1892
1893 void InsetTabular::getSelection(LCursor & cur,
1894         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
1895 {
1896         CursorSlice const & beg = cur.selBegin();
1897         CursorSlice const & end = cur.selEnd();
1898         cs = tabular.column_of_cell(beg.idx());
1899         ce = tabular.column_of_cell(end.idx());
1900         if (cs > ce) {
1901                 ce = cs;
1902                 cs = tabular.column_of_cell(end.idx());
1903         } else {
1904                 ce = tabular.right_column_of_cell(end.idx());
1905         }
1906
1907         rs = tabular.row_of_cell(beg.idx());
1908         re = tabular.row_of_cell(end.idx());
1909         if (rs > re)
1910                 swap(rs, re);
1911 }
1912
1913
1914 LyXText * InsetTabular::getText(int idx) const
1915 {
1916         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
1917 }
1918
1919
1920 void InsetTabular::setChange(Change const & change)
1921 {
1922         for (idx_type idx = 0; idx < nargs(); ++idx)
1923                 cell(idx)->setChange(change);
1924 }
1925
1926
1927 void InsetTabular::acceptChanges()
1928 {
1929         for (idx_type idx = 0; idx < nargs(); ++idx)
1930                 cell(idx)->acceptChanges();
1931 }
1932
1933
1934 void InsetTabular::rejectChanges()
1935 {
1936         for (idx_type idx = 0; idx < nargs(); ++idx)
1937                 cell(idx)->rejectChanges();
1938 }
1939
1940
1941 bool InsetTabular::forceDefaultParagraphs(idx_type cell) const
1942 {
1943         return tabular.getPWidth(cell).zero();
1944 }
1945
1946
1947 bool InsetTabular::insertAsciiString(BufferView & bv, docstring const & buf,
1948                                      bool usePaste)
1949 {
1950         if (buf.length() <= 0)
1951                 return true;
1952
1953         Buffer const & buffer = *bv.buffer();
1954
1955         col_type cols = 1;
1956         row_type rows = 1;
1957         col_type maxCols = 1;
1958         docstring::size_type const len = buf.length();
1959         docstring::size_type p = 0;
1960
1961         while (p < len &&
1962                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
1963                 switch (buf[p]) {
1964                 case '\t':
1965                         ++cols;
1966                         break;
1967                 case '\n':
1968                         if (p + 1 < len)
1969                                 ++rows;
1970                         maxCols = max(cols, maxCols);
1971                         cols = 1;
1972                         break;
1973                 }
1974                 ++p;
1975         }
1976         maxCols = max(cols, maxCols);
1977         LyXTabular * loctab;
1978         idx_type cell = 0;
1979         col_type ocol = 0;
1980         row_type row = 0;
1981         if (usePaste) {
1982                 paste_tabular.reset(
1983                         new LyXTabular(buffer.params(), rows, maxCols));
1984                 loctab = paste_tabular.get();
1985                 cols = 0;
1986                 dirtyTabularStack(true);
1987         } else {
1988                 loctab = &tabular;
1989                 cell = bv.cursor().idx();
1990                 ocol = tabular.column_of_cell(cell);
1991                 row = tabular.row_of_cell(cell);
1992         }
1993
1994         docstring::size_type op = 0;
1995         idx_type const cells = loctab->getNumberOfCells();
1996         p = 0;
1997         cols = ocol;
1998         rows = loctab->rows();
1999         col_type const columns = loctab->columns();
2000
2001         while (cell < cells && p < len && row < rows &&
2002                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
2003         {
2004                 if (p >= len)
2005                         break;
2006                 switch (buf[p]) {
2007                 case '\t':
2008                         // we can only set this if we are not too far right
2009                         if (cols < columns) {
2010                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
2011                                 Paragraph & par = inset->text_.getPar(0);
2012                                 LyXFont const font = inset->text_.getFont(buffer, par, 0);
2013                                 inset->setText(buf.substr(op, p - op), font,
2014                                                buffer.params().trackChanges);
2015                                 ++cols;
2016                                 ++cell;
2017                         }
2018                         break;
2019                 case '\n':
2020                         // we can only set this if we are not too far right
2021                         if (cols < columns) {
2022                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
2023                                 Paragraph & par = inset->text_.getPar(0);
2024                                 LyXFont const font = inset->text_.getFont(buffer, par, 0);
2025                                 inset->setText(buf.substr(op, p - op), font,
2026                                                buffer.params().trackChanges);
2027                         }
2028                         cols = ocol;
2029                         ++row;
2030                         if (row < rows)
2031                                 cell = loctab->getCellNumber(row, cols);
2032                         break;
2033                 }
2034                 ++p;
2035                 op = p;
2036         }
2037         // check for the last cell if there is no trailing '\n'
2038         if (cell < cells && op < len) {
2039                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
2040                 Paragraph & par = inset->text_.getPar(0);
2041                 LyXFont const font = inset->text_.getFont(buffer, par, 0);
2042                 inset->setText(buf.substr(op, len - op), font,
2043                         buffer.params().trackChanges);
2044         }
2045         return true;
2046 }
2047
2048
2049 void InsetTabular::addPreview(PreviewLoader & loader) const
2050 {
2051         row_type const rows = tabular.rows();
2052         col_type const columns = tabular.columns();
2053         for (row_type i = 0; i < rows; ++i) {
2054                 for (col_type j = 0; j < columns; ++j)
2055                         tabular.getCellInset(i, j)->addPreview(loader);
2056         }
2057 }
2058
2059
2060 bool InsetTabular::tablemode(LCursor & cur) const
2061 {
2062         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
2063 }
2064
2065
2066
2067
2068
2069 string const InsetTabularMailer::name_("tabular");
2070
2071 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
2072         : inset_(const_cast<InsetTabular &>(inset))
2073 {}
2074
2075
2076 string const InsetTabularMailer::inset2string(Buffer const &) const
2077 {
2078         return params2string(inset_);
2079 }
2080
2081
2082 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
2083 {
2084         istringstream data(in);
2085         LyXLex lex(0,0);
2086         lex.setStream(data);
2087
2088         if (in.empty())
2089                 return;
2090
2091         string token;
2092         lex >> token;
2093         if (!lex || token != name_)
2094                 return print_mailer_error("InsetTabularMailer", in, 1,
2095                                           name_);
2096
2097         // This is part of the inset proper that is usually swallowed
2098         // by Buffer::readInset
2099         lex >> token;
2100         if (!lex || token != "Tabular")
2101                 return print_mailer_error("InsetTabularMailer", in, 2,
2102                                           "Tabular");
2103
2104         Buffer const & buffer = inset.buffer();
2105         inset.read(buffer, lex);
2106 }
2107
2108
2109 string const InsetTabularMailer::params2string(InsetTabular const & inset)
2110 {
2111         ostringstream data;
2112         data << name_ << ' ';
2113         inset.write(inset.buffer(), data);
2114         data << "\\end_inset\n";
2115         return data.str();
2116 }
2117
2118
2119 } // namespace lyx