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