]> git.lyx.org Git - lyx.git/blob - src/insets/insettabular.C
This commit cleans up everything related to singleton. The other important change...
[lyx.git] / src / insets / insettabular.C
1 /**
2  * \file insettabular.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "insettabular.h"
14
15 #include "buffer.h"
16 #include "bufferparams.h"
17 #include "BufferView.h"
18 #include "cursor.h"
19 #include "CutAndPaste.h"
20 #include "coordcache.h"
21 #include "debug.h"
22 #include "dispatchresult.h"
23 #include "funcrequest.h"
24 #include "FuncStatus.h"
25 #include "gettext.h"
26 #include "language.h"
27 #include "LColor.h"
28 #include "lyx_cb.h"
29 #include "lyxlex.h"
30 #include "metricsinfo.h"
31 #include "outputparams.h"
32 #include "paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "undo.h"
36
37 #include "support/convert.h"
38
39 #include "frontends/Alert.h"
40 #include "frontends/Clipboard.h"
41 #include "frontends/Painter.h"
42 #include "frontends/Selection.h"
43 #include "frontends/nullpainter.h"
44
45 #include <sstream>
46 #include <iostream>
47 #include <limits>
48
49 using lyx::docstring;
50
51 using lyx::cap::dirtyTabularStack;
52 using lyx::cap::tabularStackDirty;
53
54 using lyx::graphics::PreviewLoader;
55
56 using lyx::support::ltrim;
57
58 using lyx::frontend::Painter;
59 using lyx::frontend::Clipboard;
60
61 using boost::shared_ptr;
62
63 using std::auto_ptr;
64 using std::endl;
65 using std::max;
66 using std::string;
67 using std::istringstream;
68 using std::ostream;
69 using std::ostringstream;
70 using std::swap;
71 using std::vector;
72
73 namespace Alert = lyx::frontend::Alert;
74
75
76 namespace {
77
78 int const ADD_TO_HEIGHT = 2;
79 int const ADD_TO_TABULAR_WIDTH = 2;
80 int const default_line_space = 10;
81
82 ///
83 boost::scoped_ptr<LyXTabular> paste_tabular;
84
85
86 struct TabularFeature {
87         LyXTabular::Feature action;
88         string feature;
89 };
90
91
92 TabularFeature tabularFeature[] =
93 {
94         { LyXTabular::APPEND_ROW, "append-row" },
95         { LyXTabular::APPEND_COLUMN, "append-column" },
96         { LyXTabular::DELETE_ROW, "delete-row" },
97         { LyXTabular::DELETE_COLUMN, "delete-column" },
98         { LyXTabular::COPY_ROW, "copy-row" },
99         { LyXTabular::COPY_COLUMN, "copy-column" },
100         { LyXTabular::TOGGLE_LINE_TOP, "toggle-line-top" },
101         { LyXTabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
102         { LyXTabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
103         { LyXTabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
104         { LyXTabular::ALIGN_LEFT, "align-left" },
105         { LyXTabular::ALIGN_RIGHT, "align-right" },
106         { LyXTabular::ALIGN_CENTER, "align-center" },
107         { LyXTabular::ALIGN_BLOCK, "align-block" },
108         { LyXTabular::VALIGN_TOP, "valign-top" },
109         { LyXTabular::VALIGN_BOTTOM, "valign-bottom" },
110         { LyXTabular::VALIGN_MIDDLE, "valign-middle" },
111         { LyXTabular::M_TOGGLE_LINE_TOP, "m-toggle-line-top" },
112         { LyXTabular::M_TOGGLE_LINE_BOTTOM, "m-toggle-line-bottom" },
113         { LyXTabular::M_TOGGLE_LINE_LEFT, "m-toggle-line-left" },
114         { LyXTabular::M_TOGGLE_LINE_RIGHT, "m-toggle-line-right" },
115         { LyXTabular::M_ALIGN_LEFT, "m-align-left" },
116         { LyXTabular::M_ALIGN_RIGHT, "m-align-right" },
117         { LyXTabular::M_ALIGN_CENTER, "m-align-center" },
118         { LyXTabular::M_VALIGN_TOP, "m-valign-top" },
119         { LyXTabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
120         { LyXTabular::M_VALIGN_MIDDLE, "m-valign-middle" },
121         { LyXTabular::MULTICOLUMN, "multicolumn" },
122         { LyXTabular::SET_ALL_LINES, "set-all-lines" },
123         { LyXTabular::UNSET_ALL_LINES, "unset-all-lines" },
124         { LyXTabular::SET_LONGTABULAR, "set-longtabular" },
125         { LyXTabular::UNSET_LONGTABULAR, "unset-longtabular" },
126         { LyXTabular::SET_PWIDTH, "set-pwidth" },
127         { LyXTabular::SET_MPWIDTH, "set-mpwidth" },
128         { LyXTabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
129         { LyXTabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
130         { LyXTabular::SET_ROTATE_CELL, "set-rotate-cell" },
131         { LyXTabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
132         { LyXTabular::SET_USEBOX, "set-usebox" },
133         { LyXTabular::SET_LTHEAD, "set-lthead" },
134         { LyXTabular::UNSET_LTHEAD, "unset-lthead" },
135         { LyXTabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
136         { LyXTabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
137         { LyXTabular::SET_LTFOOT, "set-ltfoot" },
138         { LyXTabular::UNSET_LTFOOT, "unset-ltfoot" },
139         { LyXTabular::SET_LTLASTFOOT, "set-ltlastfoot" },
140         { LyXTabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
141         { LyXTabular::SET_LTNEWPAGE, "set-ltnewpage" },
142         { LyXTabular::SET_SPECIAL_COLUMN, "set-special-column" },
143         { LyXTabular::SET_SPECIAL_MULTI, "set-special-multi" },
144         { LyXTabular::SET_BOOKTABS, "set-booktabs" },
145         { LyXTabular::UNSET_BOOKTABS, "unset-booktabs" },
146         { LyXTabular::SET_TOP_SPACE, "set-top-space" },
147         { LyXTabular::SET_BOTTOM_SPACE, "set-bottom-space" },
148         { LyXTabular::SET_INTERLINE_SPACE, "set-interline-space" },
149         { LyXTabular::LAST_ACTION, "" }
150 };
151
152
153 class FeatureEqual : public std::unary_function<TabularFeature, bool> {
154 public:
155         FeatureEqual(LyXTabular::Feature feature)
156                 : feature_(feature) {}
157         bool operator()(TabularFeature const & tf) const {
158                 return tf.action == feature_;
159         }
160 private:
161         LyXTabular::Feature feature_;
162 };
163
164 } // namespace anon
165
166
167 string const featureAsString(LyXTabular::Feature feature)
168 {
169         TabularFeature * end = tabularFeature +
170                 sizeof(tabularFeature) / sizeof(TabularFeature);
171         TabularFeature * it = std::find_if(tabularFeature, end,
172                                            FeatureEqual(feature));
173         return (it == end) ? string() : it->feature;
174 }
175
176
177 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                         theClipboard().get() :
704                         theSelection().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                         LCursor tmpcur = cur;
758                         for (row_type i = rs; i <= re; ++i) {
759                                 for (col_type j = cs; j <= ce; ++j) {
760                                         // cursor follows cell:
761                                         tmpcur.idx() = tabular.getCellNumber(i, j);
762                                         // select this cell only:
763                                         tmpcur.pit() = 0;
764                                         tmpcur.pos() = 0;
765                                         tmpcur.resetAnchor();
766                                         tmpcur.pit() = tmpcur.lastpit();
767                                         tmpcur.pos() = tmpcur.top().lastpos();
768                                         tmpcur.setCursor(tmpcur);
769                                         tmpcur.setSelection();
770                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
771                                 }
772                         }
773                         break;
774                 } else {
775                         cell(cur.idx())->dispatch(cur, cmd);
776                         break;
777                 }
778         default:
779                 // we try to handle this event in the insets dispatch function.
780                 cell(cur.idx())->dispatch(cur, cmd);
781                 break;
782         }
783
784         resetPos(cur);
785         InsetTabularMailer(*this).updateDialog(&cur.bv());
786 }
787
788
789 // function sets an object as defined in func_status.h:
790 // states OK, Unknown, Disabled, On, Off.
791 bool InsetTabular::getStatus(LCursor & cur, FuncRequest const & cmd,
792         FuncStatus & status) const
793 {
794         switch (cmd.action) {
795         case LFUN_TABULAR_FEATURE: {
796                 int action = LyXTabular::LAST_ACTION;
797                 int i = 0;
798                 for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
799                         string const tmp = tabularFeature[i].feature;
800                         if (tmp == lyx::to_utf8(cmd.argument()).substr(0, tmp.length())) {
801                                 action = tabularFeature[i].action;
802                                 break;
803                         }
804                 }
805                 if (action == LyXTabular::LAST_ACTION) {
806                         status.clear();
807                         status.unknown(true);
808                         return true;
809                 }
810
811                 string const argument
812                         = ltrim(lyx::to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
813
814                 row_type sel_row_start = 0;
815                 row_type sel_row_end = 0;
816                 col_type dummy;
817                 LyXTabular::ltType dummyltt;
818                 bool flag = true;
819
820                 getSelection(cur, sel_row_start, sel_row_end, dummy, dummy);
821
822                 switch (action) {
823                 case LyXTabular::SET_PWIDTH:
824                 case LyXTabular::SET_MPWIDTH:
825                 case LyXTabular::SET_SPECIAL_COLUMN:
826                 case LyXTabular::SET_SPECIAL_MULTI:
827                 case LyXTabular::APPEND_ROW:
828                 case LyXTabular::APPEND_COLUMN:
829                 case LyXTabular::DELETE_ROW:
830                 case LyXTabular::DELETE_COLUMN:
831                 case LyXTabular::COPY_ROW:
832                 case LyXTabular::COPY_COLUMN:
833                 case LyXTabular::SET_ALL_LINES:
834                 case LyXTabular::UNSET_ALL_LINES:
835                 case LyXTabular::SET_TOP_SPACE:
836                 case LyXTabular::SET_BOTTOM_SPACE:
837                 case LyXTabular::SET_INTERLINE_SPACE:
838                         status.clear();
839                         return true;
840
841                 case LyXTabular::MULTICOLUMN:
842                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
843                         break;
844
845                 case LyXTabular::M_TOGGLE_LINE_TOP:
846                         flag = false;
847                 case LyXTabular::TOGGLE_LINE_TOP:
848                         status.setOnOff(tabular.topLine(cur.idx(), flag));
849                         break;
850
851                 case LyXTabular::M_TOGGLE_LINE_BOTTOM:
852                         flag = false;
853                 case LyXTabular::TOGGLE_LINE_BOTTOM:
854                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
855                         break;
856
857                 case LyXTabular::M_TOGGLE_LINE_LEFT:
858                         flag = false;
859                 case LyXTabular::TOGGLE_LINE_LEFT:
860                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
861                         break;
862
863                 case LyXTabular::M_TOGGLE_LINE_RIGHT:
864                         flag = false;
865                 case LyXTabular::TOGGLE_LINE_RIGHT:
866                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
867                         break;
868
869                 case LyXTabular::M_ALIGN_LEFT:
870                         flag = false;
871                 case LyXTabular::ALIGN_LEFT:
872                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
873                         break;
874
875                 case LyXTabular::M_ALIGN_RIGHT:
876                         flag = false;
877                 case LyXTabular::ALIGN_RIGHT:
878                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
879                         break;
880
881                 case LyXTabular::M_ALIGN_CENTER:
882                         flag = false;
883                 case LyXTabular::ALIGN_CENTER:
884                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
885                         break;
886
887                 case LyXTabular::ALIGN_BLOCK:
888                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
889                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
890                         break;
891
892                 case LyXTabular::M_VALIGN_TOP:
893                         flag = false;
894                 case LyXTabular::VALIGN_TOP:
895                         status.setOnOff(
896                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_TOP);
897                         break;
898
899                 case LyXTabular::M_VALIGN_BOTTOM:
900                         flag = false;
901                 case LyXTabular::VALIGN_BOTTOM:
902                         status.setOnOff(
903                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_BOTTOM);
904                         break;
905
906                 case LyXTabular::M_VALIGN_MIDDLE:
907                         flag = false;
908                 case LyXTabular::VALIGN_MIDDLE:
909                         status.setOnOff(
910                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_MIDDLE);
911                         break;
912
913                 case LyXTabular::SET_LONGTABULAR:
914                         status.setOnOff(tabular.isLongTabular());
915                         break;
916
917                 case LyXTabular::UNSET_LONGTABULAR:
918                         status.setOnOff(!tabular.isLongTabular());
919                         break;
920
921                 case LyXTabular::SET_ROTATE_TABULAR:
922                         status.setOnOff(tabular.getRotateTabular());
923                         break;
924
925                 case LyXTabular::UNSET_ROTATE_TABULAR:
926                         status.setOnOff(!tabular.getRotateTabular());
927                         break;
928
929                 case LyXTabular::SET_ROTATE_CELL:
930                         status.setOnOff(tabular.getRotateCell(cur.idx()));
931                         break;
932
933                 case LyXTabular::UNSET_ROTATE_CELL:
934                         status.setOnOff(!tabular.getRotateCell(cur.idx()));
935                         break;
936
937                 case LyXTabular::SET_USEBOX:
938                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
939                         break;
940
941                 case LyXTabular::SET_LTFIRSTHEAD:
942                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
943                         break;
944
945                 case LyXTabular::UNSET_LTFIRSTHEAD:
946                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
947                         break;
948
949                 case LyXTabular::SET_LTHEAD:
950                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
951                         break;
952
953                 case LyXTabular::UNSET_LTHEAD:
954                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
955                         break;
956
957                 case LyXTabular::SET_LTFOOT:
958                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
959                         break;
960
961                 case LyXTabular::UNSET_LTFOOT:
962                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
963                         break;
964
965                 case LyXTabular::SET_LTLASTFOOT:
966                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
967                         break;
968
969                 case LyXTabular::UNSET_LTLASTFOOT:
970                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
971                         break;
972
973                 case LyXTabular::SET_LTNEWPAGE:
974                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
975                         break;
976
977                 case LyXTabular::SET_BOOKTABS:
978                         status.setOnOff(tabular.useBookTabs());
979                         break;
980
981                 case LyXTabular::UNSET_BOOKTABS:
982                         status.setOnOff(!tabular.useBookTabs());
983                         break;
984
985                 default:
986                         status.clear();
987                         status.enabled(false);
988                         break;
989                 }
990                 return true;
991         }
992
993         // These are only enabled inside tabular
994         case LFUN_CELL_BACKWARD:
995         case LFUN_CELL_FORWARD:
996                 status.enabled(true);
997                 return true;
998
999         // disable these with multiple cells selected
1000         case LFUN_INSET_INSERT:
1001         case LFUN_TABULAR_INSERT:
1002         case LFUN_CHARSTYLE_INSERT:
1003         case LFUN_FLOAT_INSERT:
1004         case LFUN_FLOAT_WIDE_INSERT:
1005         case LFUN_FOOTNOTE_INSERT:
1006         case LFUN_MARGINALNOTE_INSERT:
1007         case LFUN_MATH_INSERT:
1008         case LFUN_MATH_MODE:
1009         case LFUN_MATH_MUTATE:
1010         case LFUN_MATH_DISPLAY:
1011         case LFUN_NOTE_INSERT:
1012         case LFUN_OPTIONAL_INSERT:
1013         case LFUN_BOX_INSERT:
1014         case LFUN_BRANCH_INSERT:
1015         case LFUN_WRAP_INSERT:
1016         case LFUN_ERT_INSERT: {
1017                 if (tablemode(cur)) {
1018                         status.enabled(false);
1019                         return true;
1020                 } else
1021                         return cell(cur.idx())->getStatus(cur, cmd, status);
1022         }
1023
1024         // disable in non-fixed-width cells
1025         case LFUN_BREAK_LINE:
1026         case LFUN_BREAK_PARAGRAPH:
1027         case LFUN_BREAK_PARAGRAPH_KEEP_LAYOUT:
1028         case LFUN_BREAK_PARAGRAPH_SKIP: {
1029                 if (tabular.getPWidth(cur.idx()).zero()) {
1030                         status.enabled(false);
1031                         return true;
1032                 } else
1033                         return cell(cur.idx())->getStatus(cur, cmd, status);
1034         }
1035
1036         case LFUN_PASTE:
1037                 if (tabularStackDirty()) {
1038                         status.enabled(true);
1039                         return true;
1040                 }
1041
1042         case LFUN_INSET_MODIFY:
1043                 if (translate(cmd.getArg(0)) == TABULAR_CODE) {
1044                         status.enabled(true);
1045                         return true;
1046                 }
1047                 // Fall through
1048
1049         default:
1050                 // we try to handle this event in the insets dispatch function.
1051                 return cell(cur.idx())->getStatus(cur, cmd, status);
1052         }
1053 }
1054
1055
1056 int InsetTabular::latex(Buffer const & buf, ostream & os,
1057                         OutputParams const & runparams) const
1058 {
1059         return tabular.latex(buf, os, runparams);
1060 }
1061
1062
1063 int InsetTabular::plaintext(Buffer const & buf, ostream & os,
1064                         OutputParams const & runparams) const
1065 {
1066         int const dp = runparams.linelen ? runparams.depth : 0;
1067         return tabular.plaintext(buf, os, runparams, dp, false, 0);
1068 }
1069
1070
1071 int InsetTabular::docbook(Buffer const & buf, ostream & os,
1072                           OutputParams const & runparams) const
1073 {
1074         int ret = 0;
1075         InsetBase * master = 0;
1076
1077 #ifdef WITH_WARNINGS
1078 #warning Why not pass a proper DocIterator here?
1079 #endif
1080 #if 0
1081         // if the table is inside a float it doesn't need the informaltable
1082         // wrapper. Search for it.
1083         for (master = owner(); master; master = master->owner())
1084                 if (master->lyxCode() == InsetBase::FLOAT_CODE)
1085                         break;
1086 #endif
1087
1088         if (!master) {
1089                 os << "<informaltable>";
1090                 ++ret;
1091         }
1092         ret += tabular.docbook(buf, os, runparams);
1093         if (!master) {
1094                 os << "</informaltable>";
1095                 ++ret;
1096         }
1097         return ret;
1098 }
1099
1100
1101 void InsetTabular::validate(LaTeXFeatures & features) const
1102 {
1103         tabular.validate(features);
1104 }
1105
1106
1107 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
1108 {
1109         return tabular.getCellInset(idx);
1110 }
1111
1112
1113 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
1114 {
1115         return tabular.getCellInset(idx);
1116 }
1117
1118
1119 void InsetTabular::cursorPos
1120         (CursorSlice const & sl, bool boundary, int & x, int & y) const
1121 {
1122         cell(sl.idx())->cursorPos(sl, boundary, x, y);
1123
1124         // y offset     correction
1125         int const row = tabular.row_of_cell(sl.idx());
1126         for (int i = 0; i <= row; ++i) {
1127                 if (i != 0) {
1128                         y += tabular.getAscentOfRow(i);
1129                         y += tabular.getAdditionalHeight(i);
1130                 }
1131                 if (i != row)
1132                         y += tabular.getDescentOfRow(i);
1133         }
1134
1135         // x offset correction
1136         int const col = tabular.column_of_cell(sl.idx());
1137         int idx = tabular.getCellNumber(row, 0);
1138         for (int j = 0; j < col; ++j) {
1139                 if (tabular.isPartOfMultiColumn(row, j))
1140                         continue;
1141                 x += tabular.getWidthOfColumn(idx);
1142                 ++idx;
1143         }
1144         x += tabular.getBeginningOfTextInCell(idx);
1145         x += ADD_TO_TABULAR_WIDTH;
1146         x += scx_;
1147 }
1148
1149
1150 int InsetTabular::dist(idx_type const cell, int x, int y) const
1151 {
1152         int xx = 0;
1153         int yy = 0;
1154         InsetBase const & inset = *tabular.getCellInset(cell);
1155         Point o = theCoords.getInsets().xy(&inset);
1156         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
1157         int const xend = xbeg + tabular.getWidthOfColumn(cell);
1158         row_type const row = tabular.row_of_cell(cell);
1159         int const ybeg = o.y_ - tabular.getAscentOfRow(row) -
1160                          tabular.getAdditionalHeight(row);
1161         int const yend = o.y_ + tabular.getDescentOfRow(row);
1162
1163         if (x < xbeg)
1164                 xx = xbeg - x;
1165         else if (x > xend)
1166                 xx = x - xend;
1167
1168         if (y < ybeg)
1169                 yy = ybeg - y;
1170         else if (y > yend)
1171                 yy = y - yend;
1172
1173         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
1174         //       << " ybeg=" << ybeg << " yend=" << yend
1175         //       << " xx=" << xx << " yy=" << yy
1176         //       << " dist=" << xx + yy << endl;
1177         return xx + yy;
1178 }
1179
1180
1181 InsetBase * InsetTabular::editXY(LCursor & cur, int x, int y)
1182 {
1183         //lyxerr << "InsetTabular::editXY: " << this << endl;
1184         cur.selection() = false;
1185         cur.push(*this);
1186         cur.idx() = getNearestCell(x, y);
1187         resetPos(cur);
1188         return cell(cur.idx())->text_.editXY(cur, x, y);
1189 }
1190
1191
1192 void InsetTabular::setCursorFromCoordinates(LCursor & cur, int x, int y) const
1193 {
1194         cur.idx() = getNearestCell(x, y);
1195         cell(cur.idx())->text_.setCursorFromCoordinates(cur, x, y);
1196 }
1197
1198
1199 InsetTabular::idx_type InsetTabular::getNearestCell(int x, int y) const
1200 {
1201         idx_type idx_min = 0;
1202         int dist_min = std::numeric_limits<int>::max();
1203         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1204                 if (theCoords.getInsets().has(tabular.getCellInset(i).get())) {
1205                         int const d = dist(i, x, y);
1206                         if (d < dist_min) {
1207                                 dist_min = d;
1208                                 idx_min = i;
1209                         }
1210                 }
1211         }
1212         return idx_min;
1213 }
1214
1215
1216 int InsetTabular::getCellXPos(idx_type const cell) const
1217 {
1218         idx_type c = cell;
1219
1220         for (; !tabular.isFirstCellInRow(c); --c)
1221                 ;
1222         int lx = tabular.getWidthOfColumn(cell);
1223         for (; c < cell; ++c)
1224                 lx += tabular.getWidthOfColumn(c);
1225
1226         return lx - tabular.getWidthOfColumn(cell);
1227 }
1228
1229
1230 void InsetTabular::resetPos(LCursor & cur) const
1231 {
1232         BufferView & bv = cur.bv();
1233         int const maxwidth = bv.workWidth();
1234
1235         if (&cur.inset() != this) {
1236                 scx_ = 0;
1237         } else {
1238                 int const X1 = 0;
1239                 int const X2 = maxwidth;
1240                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
1241                 int const x1 = xo() + getCellXPos(cur.idx()) + offset;
1242                 int const x2 = x1 + tabular.getWidthOfColumn(cur.idx());
1243
1244                 if (x1 < X1)
1245                         scx_ = X1 + 20 - x1;
1246                 else if (x2 > X2)
1247                         scx_ = X2 - 20 - x2;
1248                 else
1249                         scx_ = 0;
1250         }
1251
1252         cur.needsUpdate();
1253
1254         InsetTabularMailer(*this).updateDialog(&bv);
1255 }
1256
1257
1258 void InsetTabular::moveNextCell(LCursor & cur)
1259 {
1260         if (isRightToLeft(cur)) {
1261                 if (tabular.isFirstCellInRow(cur.idx())) {
1262                         row_type const row = tabular.row_of_cell(cur.idx());
1263                         if (row == tabular.rows() - 1)
1264                                 return;
1265                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
1266                 } else {
1267                         if (cur.idx() == 0)
1268                                 return;
1269                         --cur.idx();
1270                 }
1271         } else {
1272                 if (tabular.isLastCell(cur.idx()))
1273                         return;
1274                 ++cur.idx();
1275         }
1276         cur.pit() = 0;
1277         cur.pos() = 0;
1278         resetPos(cur);
1279 }
1280
1281
1282 void InsetTabular::movePrevCell(LCursor & cur)
1283 {
1284         if (isRightToLeft(cur)) {
1285                 if (tabular.isLastCellInRow(cur.idx())) {
1286                         row_type const row = tabular.row_of_cell(cur.idx());
1287                         if (row == 0)
1288                                 return;
1289                         cur.idx() = tabular.getFirstCellInRow(row);
1290                         cur.idx() = tabular.getCellAbove(cur.idx());
1291                 } else {
1292                         if (tabular.isLastCell(cur.idx()))
1293                                 return;
1294                         ++cur.idx();
1295                 }
1296         } else {
1297                 if (cur.idx() == 0) // first cell
1298                         return;
1299                 --cur.idx();
1300         }
1301         cur.pit() = cur.lastpit();
1302         cur.pos() = cur.lastpos();
1303         resetPos(cur);
1304 }
1305
1306
1307 bool InsetTabular::tabularFeatures(LCursor & cur, string const & what)
1308 {
1309         LyXTabular::Feature action = LyXTabular::LAST_ACTION;
1310
1311         int i = 0;
1312         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
1313                 string const tmp = tabularFeature[i].feature;
1314
1315                 if (tmp == what.substr(0, tmp.length())) {
1316                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
1317                         //tabularFeatures[i].feature.length())) {
1318                         action = tabularFeature[i].action;
1319                         break;
1320                 }
1321         }
1322         if (action == LyXTabular::LAST_ACTION)
1323                 return false;
1324
1325         string const val =
1326                 ltrim(what.substr(tabularFeature[i].feature.length()));
1327         tabularFeatures(cur, action, val);
1328         return true;
1329 }
1330
1331
1332 namespace {
1333
1334 void checkLongtableSpecial(LyXTabular::ltType & ltt,
1335                           string const & special, bool & flag)
1336 {
1337         if (special == "dl_above") {
1338                 ltt.topDL = flag;
1339                 ltt.set = false;
1340         } else if (special == "dl_below") {
1341                 ltt.bottomDL = flag;
1342                 ltt.set = false;
1343         } else if (special == "empty") {
1344                 ltt.empty = flag;
1345                 ltt.set = false;
1346         } else if (flag) {
1347                 ltt.empty = false;
1348                 ltt.set = true;
1349         }
1350 }
1351
1352 } // anon namespace
1353
1354
1355 void InsetTabular::tabularFeatures(LCursor & cur,
1356         LyXTabular::Feature feature, string const & value)
1357 {
1358         BufferView & bv = cur.bv();
1359         col_type sel_col_start;
1360         col_type sel_col_end;
1361         row_type sel_row_start;
1362         row_type sel_row_end;
1363         bool setLines = false;
1364         LyXAlignment setAlign = LYX_ALIGN_LEFT;
1365         LyXTabular::VAlignment setVAlign = LyXTabular::LYX_VALIGN_TOP;
1366
1367         switch (feature) {
1368
1369         case LyXTabular::M_ALIGN_LEFT:
1370         case LyXTabular::ALIGN_LEFT:
1371                 setAlign = LYX_ALIGN_LEFT;
1372                 break;
1373
1374         case LyXTabular::M_ALIGN_RIGHT:
1375         case LyXTabular::ALIGN_RIGHT:
1376                 setAlign = LYX_ALIGN_RIGHT;
1377                 break;
1378
1379         case LyXTabular::M_ALIGN_CENTER:
1380         case LyXTabular::ALIGN_CENTER:
1381                 setAlign = LYX_ALIGN_CENTER;
1382                 break;
1383
1384         case LyXTabular::ALIGN_BLOCK:
1385                 setAlign = LYX_ALIGN_BLOCK;
1386                 break;
1387
1388         case LyXTabular::M_VALIGN_TOP:
1389         case LyXTabular::VALIGN_TOP:
1390                 setVAlign = LyXTabular::LYX_VALIGN_TOP;
1391                 break;
1392
1393         case LyXTabular::M_VALIGN_BOTTOM:
1394         case LyXTabular::VALIGN_BOTTOM:
1395                 setVAlign = LyXTabular::LYX_VALIGN_BOTTOM;
1396                 break;
1397
1398         case LyXTabular::M_VALIGN_MIDDLE:
1399         case LyXTabular::VALIGN_MIDDLE:
1400                 setVAlign = LyXTabular::LYX_VALIGN_MIDDLE;
1401                 break;
1402
1403         default:
1404                 break;
1405         }
1406
1407         recordUndoInset(cur, Undo::ATOMIC);
1408
1409         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1410         row_type const row = tabular.row_of_cell(cur.idx());
1411         col_type const column = tabular.column_of_cell(cur.idx());
1412         bool flag = true;
1413         LyXTabular::ltType ltt;
1414
1415         switch (feature) {
1416
1417         case LyXTabular::SET_PWIDTH: {
1418                 LyXLength const len(value);
1419                 tabular.setColumnPWidth(cur, cur.idx(), len);
1420                 if (len.zero()
1421                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
1422                         tabularFeatures(cur, LyXTabular::ALIGN_CENTER, string());
1423                 break;
1424         }
1425
1426         case LyXTabular::SET_MPWIDTH:
1427                 tabular.setMColumnPWidth(cur, cur.idx(), LyXLength(value));
1428                 break;
1429
1430         case LyXTabular::SET_SPECIAL_COLUMN:
1431         case LyXTabular::SET_SPECIAL_MULTI:
1432                 tabular.setAlignSpecial(cur.idx(),value,feature);
1433                 break;
1434
1435         case LyXTabular::APPEND_ROW:
1436                 // append the row into the tabular
1437                 tabular.appendRow(bv.buffer()->params(), cur.idx());
1438                 break;
1439
1440         case LyXTabular::APPEND_COLUMN:
1441                 // append the column into the tabular
1442                 tabular.appendColumn(bv.buffer()->params(), cur.idx());
1443                 cur.idx() = tabular.getCellNumber(row, column);
1444                 break;
1445
1446         case LyXTabular::DELETE_ROW:
1447                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1448                         tabular.deleteRow(sel_row_start);
1449                 if (sel_row_start >= tabular.rows())
1450                         --sel_row_start;
1451                 cur.idx() = tabular.getCellNumber(sel_row_start, column);
1452                 cur.pit() = 0;
1453                 cur.pos() = 0;
1454                 cur.selection() = false;
1455                 break;
1456
1457         case LyXTabular::DELETE_COLUMN:
1458                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
1459                         tabular.deleteColumn(sel_col_start);
1460                 if (sel_col_start >= tabular.columns())
1461                         --sel_col_start;
1462                 cur.idx() = tabular.getCellNumber(row, sel_col_start);
1463                 cur.pit() = 0;
1464                 cur.pos() = 0;
1465                 cur.selection() = false;
1466                 break;
1467
1468         case LyXTabular::COPY_ROW:
1469                 tabular.copyRow(bv.buffer()->params(), row);
1470                 break;
1471
1472         case LyXTabular::COPY_COLUMN:
1473                 tabular.copyColumn(bv.buffer()->params(), column);
1474                 cur.idx() = tabular.getCellNumber(row, column);
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                         // FIXME UNICODE
1564                         Alert::error(_("Error setting multicolumn"),
1565                                      _("You cannot set multicolumn vertically."));
1566                         return;
1567                 }
1568                 if (!cur.selection()) {
1569                         // just multicol for one single cell
1570                         // check whether we are completely in a multicol
1571                         if (tabular.isMultiColumn(cur.idx()))
1572                                 tabular.unsetMultiColumn(cur.idx());
1573                         else
1574                                 tabular.setMultiColumn(bv.buffer(), cur.idx(), 1);
1575                         break;
1576                 }
1577                 // we have a selection so this means we just add all this
1578                 // cells to form a multicolumn cell
1579                 idx_type const s_start = cur.selBegin().idx();
1580                 idx_type const s_end = cur.selEnd().idx();
1581                 tabular.setMultiColumn(bv.buffer(), s_start, s_end - s_start + 1);
1582                 cur.idx() = s_start;
1583                 cur.pit() = 0;
1584                 cur.pos() = 0;
1585                 cur.selection() = false;
1586                 break;
1587         }
1588
1589         case LyXTabular::SET_ALL_LINES:
1590                 setLines = true;
1591         case LyXTabular::UNSET_ALL_LINES:
1592                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1593                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1594                                 tabular.setAllLines(
1595                                         tabular.getCellNumber(i,j), setLines);
1596                 break;
1597
1598         case LyXTabular::SET_LONGTABULAR:
1599                 tabular.setLongTabular(true);
1600                 break;
1601
1602         case LyXTabular::UNSET_LONGTABULAR:
1603                 tabular.setLongTabular(false);
1604                 break;
1605
1606         case LyXTabular::SET_ROTATE_TABULAR:
1607                 tabular.setRotateTabular(true);
1608                 break;
1609
1610         case LyXTabular::UNSET_ROTATE_TABULAR:
1611                 tabular.setRotateTabular(false);
1612                 break;
1613
1614         case LyXTabular::SET_ROTATE_CELL:
1615                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1616                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1617                                 tabular.setRotateCell(
1618                                         tabular.getCellNumber(i, j), true);
1619                 break;
1620
1621         case LyXTabular::UNSET_ROTATE_CELL:
1622                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1623                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1624                                 tabular.setRotateCell(
1625                                         tabular.getCellNumber(i, j), false);
1626                 break;
1627
1628         case LyXTabular::SET_USEBOX: {
1629                 LyXTabular::BoxType val = LyXTabular::BoxType(convert<int>(value));
1630                 if (val == tabular.getUsebox(cur.idx()))
1631                         val = LyXTabular::BOX_NONE;
1632                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1633                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1634                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1635                 break;
1636         }
1637
1638         case LyXTabular::UNSET_LTFIRSTHEAD:
1639                 flag = false;
1640         case LyXTabular::SET_LTFIRSTHEAD:
1641                 tabular.getRowOfLTFirstHead(row, ltt);
1642                 checkLongtableSpecial(ltt, value, flag);
1643                 tabular.setLTHead(row, flag, ltt, true);
1644                 break;
1645
1646         case LyXTabular::UNSET_LTHEAD:
1647                 flag = false;
1648         case LyXTabular::SET_LTHEAD:
1649                 tabular.getRowOfLTHead(row, ltt);
1650                 checkLongtableSpecial(ltt, value, flag);
1651                 tabular.setLTHead(row, flag, ltt, false);
1652                 break;
1653
1654         case LyXTabular::UNSET_LTFOOT:
1655                 flag = false;
1656         case LyXTabular::SET_LTFOOT:
1657                 tabular.getRowOfLTFoot(row, ltt);
1658                 checkLongtableSpecial(ltt, value, flag);
1659                 tabular.setLTFoot(row, flag, ltt, false);
1660                 break;
1661
1662         case LyXTabular::UNSET_LTLASTFOOT:
1663                 flag = false;
1664         case LyXTabular::SET_LTLASTFOOT:
1665                 tabular.getRowOfLTLastFoot(row, ltt);
1666                 checkLongtableSpecial(ltt, value, flag);
1667                 tabular.setLTFoot(row, flag, ltt, true);
1668                 break;
1669
1670         case LyXTabular::SET_LTNEWPAGE:
1671                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1672                 break;
1673
1674         case LyXTabular::SET_BOOKTABS:
1675                 tabular.setBookTabs(true);
1676                 break;
1677
1678         case LyXTabular::UNSET_BOOKTABS:
1679                 tabular.setBookTabs(false);
1680                 break;
1681
1682         case LyXTabular::SET_TOP_SPACE: {
1683                 LyXLength len;
1684                 if (value == "default")
1685                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1686                                 tabular.row_info[i].top_space_default = true;
1687                 else if (isValidLength(value, &len))
1688                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1689                                 tabular.row_info[i].top_space_default = false;
1690                                 tabular.row_info[i].top_space = len;
1691                         }
1692                 else
1693                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1694                                 tabular.row_info[i].top_space_default = false;
1695                                 tabular.row_info[i].top_space = len;
1696                         }
1697                 break;
1698         }
1699
1700         case LyXTabular::SET_BOTTOM_SPACE: {
1701                 LyXLength len;
1702                 if (value == "default")
1703                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1704                                 tabular.row_info[i].bottom_space_default = true;
1705                 else if (isValidLength(value, &len))
1706                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1707                                 tabular.row_info[i].bottom_space_default = false;
1708                                 tabular.row_info[i].bottom_space = len;
1709                         }
1710                 else
1711                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1712                                 tabular.row_info[i].bottom_space_default = false;
1713                                 tabular.row_info[i].bottom_space = len;
1714                         }
1715                 break;
1716         }
1717
1718         case LyXTabular::SET_INTERLINE_SPACE: {
1719                 LyXLength len;
1720                 if (value == "default")
1721                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1722                                 tabular.row_info[i].interline_space_default = true;
1723                 else if (isValidLength(value, &len))
1724                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1725                                 tabular.row_info[i].interline_space_default = false;
1726                                 tabular.row_info[i].interline_space = len;
1727                         }
1728                 else
1729                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
1730                                 tabular.row_info[i].interline_space_default = false;
1731                                 tabular.row_info[i].interline_space = len;
1732                         }
1733                 break;
1734         }
1735
1736         // dummy stuff just to avoid warnings
1737         case LyXTabular::LAST_ACTION:
1738                 break;
1739         }
1740
1741         InsetTabularMailer(*this).updateDialog(&bv);
1742 }
1743
1744
1745 bool InsetTabular::showInsetDialog(BufferView * bv) const
1746 {
1747         InsetTabularMailer(*this).showDialog(bv);
1748         return true;
1749 }
1750
1751
1752 void InsetTabular::openLayoutDialog(BufferView * bv) const
1753 {
1754         InsetTabularMailer(*this).showDialog(bv);
1755 }
1756
1757
1758 bool InsetTabular::copySelection(LCursor & cur)
1759 {
1760         if (!cur.selection())
1761                 return false;
1762
1763         row_type rs, re;
1764         col_type cs, ce;
1765         getSelection(cur, rs, re, cs, ce);
1766
1767         paste_tabular.reset(new LyXTabular(tabular));
1768
1769         for (row_type i = 0; i < rs; ++i)
1770                 paste_tabular->deleteRow(0);
1771
1772         row_type const rows = re - rs + 1;
1773         while (paste_tabular->rows() > rows)
1774                 paste_tabular->deleteRow(rows);
1775
1776         paste_tabular->setTopLine(0, true, true);
1777         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
1778                                      true, true);
1779
1780         for (col_type i = 0; i < cs; ++i)
1781                 paste_tabular->deleteColumn(0);
1782
1783         col_type const columns = ce - cs + 1;
1784         while (paste_tabular->columns() > columns)
1785                 paste_tabular->deleteColumn(columns);
1786
1787         paste_tabular->setLeftLine(0, true, true);
1788         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
1789                                     true, true);
1790
1791         ostringstream os;
1792         OutputParams const runparams;
1793         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
1794         theClipboard().put(lyx::from_utf8(os.str()));
1795         // mark tabular stack dirty
1796         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
1797         // when we (hopefully) have a one-for-all paste mechanism.
1798         lyx::cap::dirtyTabularStack(true);
1799
1800         return true;
1801 }
1802
1803
1804 bool InsetTabular::pasteSelection(LCursor & cur)
1805 {
1806         if (!paste_tabular)
1807                 return false;
1808         col_type const actcol = tabular.column_of_cell(cur.idx());
1809         row_type const actrow = tabular.row_of_cell(cur.idx());
1810         for (row_type r1 = 0, r2 = actrow;
1811              r1 < paste_tabular->rows() && r2 < tabular.rows();
1812              ++r1, ++r2) {
1813                 for (col_type c1 = 0, c2 = actcol;
1814                     c1 < paste_tabular->columns() && c2 < tabular.columns();
1815                     ++c1, ++c2) {
1816                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
1817                             tabular.isPartOfMultiColumn(r2, c2))
1818                                 continue;
1819                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
1820                                 --c2;
1821                                 continue;
1822                         }
1823                         if (tabular.isPartOfMultiColumn(r2, c2)) {
1824                                 --c1;
1825                                 continue;
1826                         }
1827                         shared_ptr<InsetText> inset(
1828                                 new InsetText(*paste_tabular->getCellInset(r1, c1)));
1829                         tabular.setCellInset(r2, c2, inset);
1830                         inset->markNew();
1831                         cur.pos() = 0;
1832                 }
1833         }
1834         return true;
1835 }
1836
1837
1838 void InsetTabular::cutSelection(LCursor & cur)
1839 {
1840         if (!cur.selection())
1841                 return;
1842
1843         row_type rs, re;
1844         col_type cs, ce;
1845         getSelection(cur, rs, re, cs, ce);
1846         for (row_type i = rs; i <= re; ++i) {
1847                 for (col_type j = cs; j <= ce; ++j) {
1848                         shared_ptr<InsetText> t
1849                                 = cell(tabular.getCellNumber(i, j));
1850                         if (cur.buffer().params().trackChanges)
1851                                 // FIXME: Change tracking (MG)
1852                                 t->markErased(true);
1853                         else
1854                                 t->clear();
1855                 }
1856         }
1857
1858         // cursor position might be invalid now
1859         if (cur.pit() > cur.lastpit())
1860                 cur.pit() = cur.lastpit();
1861         if (cur.pos() > cur.lastpos())
1862                 cur.pos() = cur.lastpos();
1863         cur.clearSelection();
1864 }
1865
1866
1867 bool InsetTabular::isRightToLeft(LCursor & cur) const
1868 {
1869         BOOST_ASSERT(cur.depth() > 1);
1870         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
1871         LCursor::pos_type const parentpos = cur[cur.depth() - 2].pos();
1872         return parentpar.getFontSettings(cur.bv().buffer()->params(),
1873                                          parentpos).language()->rightToLeft();
1874 }
1875
1876
1877 void InsetTabular::getSelection(LCursor & cur,
1878         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
1879 {
1880         CursorSlice const & beg = cur.selBegin();
1881         CursorSlice const & end = cur.selEnd();
1882         cs = tabular.column_of_cell(beg.idx());
1883         ce = tabular.column_of_cell(end.idx());
1884         if (cs > ce) {
1885                 ce = cs;
1886                 cs = tabular.column_of_cell(end.idx());
1887         } else {
1888                 ce = tabular.right_column_of_cell(end.idx());
1889         }
1890
1891         rs = tabular.row_of_cell(beg.idx());
1892         re = tabular.row_of_cell(end.idx());
1893         if (rs > re)
1894                 swap(rs, re);
1895 }
1896
1897
1898 LyXText * InsetTabular::getText(int idx) const
1899 {
1900         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
1901 }
1902
1903
1904 void InsetTabular::markErased(bool erased)
1905 {
1906         for (idx_type idx = 0; idx < nargs(); ++idx)
1907                 cell(idx)->markErased(erased);
1908 }
1909
1910
1911 bool InsetTabular::forceDefaultParagraphs(idx_type cell) const
1912 {
1913         return tabular.getPWidth(cell).zero();
1914 }
1915
1916
1917 bool InsetTabular::insertAsciiString(BufferView & bv, docstring const & buf,
1918                                      bool usePaste)
1919 {
1920         if (buf.length() <= 0)
1921                 return true;
1922
1923         col_type cols = 1;
1924         row_type rows = 1;
1925         col_type maxCols = 1;
1926         docstring::size_type const len = buf.length();
1927         docstring::size_type p = 0;
1928
1929         while (p < len &&
1930                (p = buf.find_first_of(lyx::from_ascii("\t\n"), p)) != docstring::npos) {
1931                 switch (buf[p]) {
1932                 case '\t':
1933                         ++cols;
1934                         break;
1935                 case '\n':
1936                         if (p + 1 < len)
1937                                 ++rows;
1938                         maxCols = max(cols, maxCols);
1939                         cols = 1;
1940                         break;
1941                 }
1942                 ++p;
1943         }
1944         maxCols = max(cols, maxCols);
1945         LyXTabular * loctab;
1946         idx_type cell = 0;
1947         col_type ocol = 0;
1948         row_type row = 0;
1949         if (usePaste) {
1950                 paste_tabular.reset(
1951                         new LyXTabular(bv.buffer()->params(), rows, maxCols));
1952                 loctab = paste_tabular.get();
1953                 cols = 0;
1954                 dirtyTabularStack(true);
1955         } else {
1956                 loctab = &tabular;
1957                 cell = bv.cursor().idx();
1958                 ocol = tabular.column_of_cell(cell);
1959                 row = tabular.row_of_cell(cell);
1960         }
1961
1962         docstring::size_type op = 0;
1963         idx_type const cells = loctab->getNumberOfCells();
1964         p = 0;
1965         cols = ocol;
1966         rows = loctab->rows();
1967         col_type const columns = loctab->columns();
1968
1969         while (cell < cells && p < len && row < rows &&
1970                (p = buf.find_first_of(lyx::from_ascii("\t\n"), p)) != docstring::npos)
1971         {
1972                 if (p >= len)
1973                         break;
1974                 switch (buf[p]) {
1975                 case '\t':
1976                         // we can only set this if we are not too far right
1977                         if (cols < columns) {
1978                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
1979                                 inset->setViewCache(&bv);
1980                                 Paragraph & par = inset->text_.getPar(0);
1981                                 LyXFont const font = inset->text_.getFont(par, 0);
1982                                 inset->setText(buf.substr(op, p - op), font);
1983                                 ++cols;
1984                                 ++cell;
1985                         }
1986                         break;
1987                 case '\n':
1988                         // we can only set this if we are not too far right
1989                         if (cols < columns) {
1990                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
1991                                 inset->setViewCache(&bv);
1992                                 Paragraph & par = inset->text_.getPar(0);
1993                                 LyXFont const font = inset->text_.getFont(par, 0);
1994                                 inset->setText(buf.substr(op, p - op), font);
1995                         }
1996                         cols = ocol;
1997                         ++row;
1998                         if (row < rows)
1999                                 cell = loctab->getCellNumber(row, cols);
2000                         break;
2001                 }
2002                 ++p;
2003                 op = p;
2004         }
2005         // check for the last cell if there is no trailing '\n'
2006         if (cell < cells && op < len) {
2007                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
2008                 inset->setViewCache(&bv);
2009                 Paragraph & par = inset->text_.getPar(0);
2010                 LyXFont const font = inset->text_.getFont(par, 0);
2011                 inset->setText(buf.substr(op, len - op), font);
2012         }
2013         return true;
2014 }
2015
2016
2017 void InsetTabular::addPreview(PreviewLoader & loader) const
2018 {
2019         row_type const rows = tabular.rows();
2020         col_type const columns = tabular.columns();
2021         for (row_type i = 0; i < rows; ++i) {
2022                 for (col_type j = 0; j < columns; ++j)
2023                         tabular.getCellInset(i, j)->addPreview(loader);
2024         }
2025 }
2026
2027
2028 bool InsetTabular::tablemode(LCursor & cur) const
2029 {
2030         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
2031 }
2032
2033
2034
2035
2036
2037 string const InsetTabularMailer::name_("tabular");
2038
2039 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
2040         : inset_(const_cast<InsetTabular &>(inset))
2041 {}
2042
2043
2044 string const InsetTabularMailer::inset2string(Buffer const &) const
2045 {
2046         return params2string(inset_);
2047 }
2048
2049
2050 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
2051 {
2052         istringstream data(in);
2053         LyXLex lex(0,0);
2054         lex.setStream(data);
2055
2056         if (in.empty())
2057                 return;
2058
2059         string token;
2060         lex >> token;
2061         if (!lex || token != name_)
2062                 return print_mailer_error("InsetTabularMailer", in, 1,
2063                                           name_);
2064
2065         // This is part of the inset proper that is usually swallowed
2066         // by Buffer::readInset
2067         lex >> token;
2068         if (!lex || token != "Tabular")
2069                 return print_mailer_error("InsetTabularMailer", in, 2,
2070                                           "Tabular");
2071
2072         Buffer const & buffer = inset.buffer();
2073         inset.read(buffer, lex);
2074 }
2075
2076
2077 string const InsetTabularMailer::params2string(InsetTabular const & inset)
2078 {
2079         ostringstream data;
2080         data << name_ << ' ';
2081         inset.write(inset.buffer(), data);
2082         data << "\\end_inset\n";
2083         return data.str();
2084 }