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