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