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