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