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