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