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