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