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