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