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