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