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