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