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