]> git.lyx.org Git - lyx.git/blob - src/insets/insettabular.C
fix crash after removing a table row (again due to uncorrected cursor
[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 "debug.h"
20 #include "dispatchresult.h"
21 #include "funcrequest.h"
22 #include "FuncStatus.h"
23 #include "gettext.h"
24 #include "language.h"
25 #include "LColor.h"
26 #include "lyx_cb.h"
27 #include "lyxlex.h"
28 #include "metricsinfo.h"
29 #include "outputparams.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphParameters.h"
33 #include "undo.h"
34
35 #include "frontends/Alert.h"
36 #include "frontends/font_metrics.h"
37 #include "frontends/LyXView.h"
38 #include "frontends/Painter.h"
39
40 #include <sstream>
41 #include <iostream>
42
43 using lyx::graphics::PreviewLoader;
44
45 using lyx::support::ltrim;
46 using lyx::support::strToInt;
47 using lyx::support::strToDbl;
48
49 using std::auto_ptr;
50 using std::endl;
51 using std::max;
52 using std::string;
53 using std::istringstream;
54 using std::ostream;
55 using std::ostringstream;
56 using std::swap;
57 using std::vector;
58
59
60 namespace {
61
62 int const ADD_TO_HEIGHT = 2;
63 int const ADD_TO_TABULAR_WIDTH = 2;
64
65 ///
66 boost::scoped_ptr<LyXTabular> paste_tabular;
67
68
69 struct TabularFeature {
70         LyXTabular::Feature action;
71         string feature;
72 };
73
74
75 TabularFeature tabularFeature[] =
76 {
77         { LyXTabular::APPEND_ROW, "append-row" },
78         { LyXTabular::APPEND_COLUMN, "append-column" },
79         { LyXTabular::DELETE_ROW, "delete-row" },
80         { LyXTabular::DELETE_COLUMN, "delete-column" },
81         { LyXTabular::TOGGLE_LINE_TOP, "toggle-line-top" },
82         { LyXTabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
83         { LyXTabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
84         { LyXTabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
85         { LyXTabular::ALIGN_LEFT, "align-left" },
86         { LyXTabular::ALIGN_RIGHT, "align-right" },
87         { LyXTabular::ALIGN_CENTER, "align-center" },
88         { LyXTabular::ALIGN_BLOCK, "align-block" },
89         { LyXTabular::VALIGN_TOP, "valign-top" },
90         { LyXTabular::VALIGN_BOTTOM, "valign-bottom" },
91         { LyXTabular::VALIGN_MIDDLE, "valign-middle" },
92         { LyXTabular::M_TOGGLE_LINE_TOP, "m-toggle-line-top" },
93         { LyXTabular::M_TOGGLE_LINE_BOTTOM, "m-toggle-line-bottom" },
94         { LyXTabular::M_TOGGLE_LINE_LEFT, "m-toggle-line-left" },
95         { LyXTabular::M_TOGGLE_LINE_RIGHT, "m-toggle-line-right" },
96         { LyXTabular::M_ALIGN_LEFT, "m-align-left" },
97         { LyXTabular::M_ALIGN_RIGHT, "m-align-right" },
98         { LyXTabular::M_ALIGN_CENTER, "m-align-center" },
99         { LyXTabular::M_VALIGN_TOP, "m-valign-top" },
100         { LyXTabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
101         { LyXTabular::M_VALIGN_MIDDLE, "m-valign-middle" },
102         { LyXTabular::MULTICOLUMN, "multicolumn" },
103         { LyXTabular::SET_ALL_LINES, "set-all-lines" },
104         { LyXTabular::UNSET_ALL_LINES, "unset-all-lines" },
105         { LyXTabular::SET_LONGTABULAR, "set-longtabular" },
106         { LyXTabular::UNSET_LONGTABULAR, "unset-longtabular" },
107         { LyXTabular::SET_PWIDTH, "set-pwidth" },
108         { LyXTabular::SET_MPWIDTH, "set-mpwidth" },
109         { LyXTabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
110         { LyXTabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
111         { LyXTabular::SET_ROTATE_CELL, "set-rotate-cell" },
112         { LyXTabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
113         { LyXTabular::SET_USEBOX, "set-usebox" },
114         { LyXTabular::SET_LTHEAD, "set-lthead" },
115         { LyXTabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
116         { LyXTabular::SET_LTFOOT, "set-ltfoot" },
117         { LyXTabular::SET_LTLASTFOOT, "set-ltlastfoot" },
118         { LyXTabular::SET_LTNEWPAGE, "set-ltnewpage" },
119         { LyXTabular::SET_SPECIAL_COLUMN, "set-special-column" },
120         { LyXTabular::SET_SPECIAL_MULTI, "set-special-multi" },
121         { LyXTabular::LAST_ACTION, "" }
122 };
123
124
125 class FeatureEqual : public std::unary_function<TabularFeature, bool> {
126 public:
127         FeatureEqual(LyXTabular::Feature feature)
128                 : feature_(feature) {}
129         bool operator()(TabularFeature const & tf) const {
130                 return tf.action == feature_;
131         }
132 private:
133         LyXTabular::Feature feature_;
134 };
135
136 } // namespace anon
137
138
139 string const featureAsString(LyXTabular::Feature feature)
140 {
141         TabularFeature * end = tabularFeature +
142                 sizeof(tabularFeature) / sizeof(TabularFeature);
143         TabularFeature * it = std::find_if(tabularFeature, end,
144                                            FeatureEqual(feature));
145         return (it == end) ? string() : it->feature;
146 }
147
148
149 bool InsetTabular::hasPasteBuffer() const
150 {
151         return (paste_tabular.get() != 0);
152 }
153
154
155 InsetTabular::InsetTabular(Buffer const & buf, int rows, int columns)
156         : tabular(buf.params(), max(rows, 1), max(columns, 1)),
157           buffer_(&buf), cursorx_(0)
158 {}
159
160
161 InsetTabular::InsetTabular(InsetTabular const & tab)
162         : UpdatableInset(tab), tabular(tab.tabular),
163                 buffer_(tab.buffer_), cursorx_(0)
164 {}
165
166
167 InsetTabular::~InsetTabular()
168 {
169         InsetTabularMailer(*this).hideDialog();
170 }
171
172
173 auto_ptr<InsetBase> InsetTabular::clone() const
174 {
175         return auto_ptr<InsetBase>(new InsetTabular(*this));
176 }
177
178
179 Buffer const & InsetTabular::buffer() const
180 {
181         return *buffer_;
182 }
183
184
185 void InsetTabular::buffer(Buffer const * b)
186 {
187         buffer_ = b;
188 }
189
190
191 void InsetTabular::write(Buffer const & buf, ostream & os) const
192 {
193         os << "Tabular" << endl;
194         tabular.write(buf, os);
195 }
196
197
198 void InsetTabular::read(Buffer const & buf, LyXLex & lex)
199 {
200         bool const old_format = (lex.getString() == "\\LyXTable");
201
202         tabular.read(buf, lex);
203
204         if (old_format)
205                 return;
206
207         lex.next();
208         string token = lex.getString();
209         while (lex.isOK() && (token != "\\end_inset")) {
210                 lex.next();
211                 token = lex.getString();
212         }
213         if (token != "\\end_inset") {
214                 lex.printError("Missing \\end_inset at this point. "
215                                "Read: `$$Token'");
216         }
217 }
218
219
220 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
221 {
222         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
223         //      mi.base.textwidth << "\n";
224         if (!mi.base.bv) {
225                 lyxerr << "InsetTabular::metrics: need bv" << endl;
226                 BOOST_ASSERT(false);
227         }
228
229         for (int i = 0, cell = -1; i < tabular.rows(); ++i) {
230                 int maxAsc = 0;
231                 int maxDesc = 0;
232                 for (int j = 0; j < tabular.columns(); ++j) {
233                         if (tabular.isPartOfMultiColumn(i, j))
234                                 continue;
235                         ++cell;
236                         Dimension dim;
237                         MetricsInfo m = mi;
238                         LyXLength p_width = tabular.column_info[j].p_width;
239                         if (!p_width.zero()) {
240                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
241                         }
242                         tabular.getCellInset(cell).metrics(m, dim);
243                         maxAsc  = max(maxAsc, dim.asc);
244                         maxDesc = max(maxDesc, dim.des);
245                         tabular.setWidthOfCell(cell, dim.wid);
246                 }
247                 tabular.setAscentOfRow(i, maxAsc + ADD_TO_HEIGHT);
248                 tabular.setDescentOfRow(i, maxDesc + ADD_TO_HEIGHT);
249         }
250
251         dim.asc = tabular.getAscentOfRow(0);
252         dim.des = tabular.getHeightOfTabular() - tabular.getAscentOfRow(0) + 1;
253         dim.wid = tabular.getWidthOfTabular() + 2 * ADD_TO_TABULAR_WIDTH;
254         dim_ = dim;
255 }
256
257
258 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
259 {
260         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
261
262         BufferView * bv = pi.base.bv;
263         setPosCache(pi, x, y);
264
265         x += scroll();
266         x += ADD_TO_TABULAR_WIDTH;
267
268         int idx = 0;
269         first_visible_cell = -1;
270         for (int i = 0; i < tabular.rows(); ++i) {
271                 int nx = x;
272                 idx = tabular.getCellNumber(i, 0);
273                 if (y + tabular.getDescentOfRow(i) <= 0
274                     && y - tabular.getAscentOfRow(i) < pi.pain.paperHeight()) {
275                         y += tabular.getDescentOfRow(i)
276                                 + tabular.getAscentOfRow(i + 1)
277                                 + tabular.getAdditionalHeight(i + 1);
278                         continue;
279                 }
280                 for (int j = 0; j < tabular.columns(); ++j) {
281                         if (nx > bv->workWidth())
282                                 break;
283                         if (tabular.isPartOfMultiColumn(i, j))
284                                 continue;
285                         if (first_visible_cell < 0)
286                                 first_visible_cell = idx;
287                         if (bv->cursor().selection())
288                                 drawCellSelection(pi, nx, y, i, j, idx);
289
290                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
291                         cell(idx).draw(pi, cx, y);
292                         drawCellLines(pi.pain, nx, y, i, idx);
293                         nx += tabular.getWidthOfColumn(idx);
294                         ++idx;
295                 }
296
297 // Would be nice, but for some completely unfathomable reason,
298 // on a col resize to a new fixed width, even though the insettexts
299 // are resized, the cell isn't, but drawing all cells in a tall table
300 // has the desired effect somehow. Complete dark magic.
301 #if 0
302                 // avoiding drawing the rest of a long table is
303                 // a pretty big speedup
304                 if (y > bv->workHeight())
305                         break;
306 #endif
307
308                 y += tabular.getDescentOfRow(i) +
309                         tabular.getAscentOfRow(i + 1) +
310                         tabular.getAdditionalHeight(i + 1);
311         }
312 }
313
314
315 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
316                                  int row, int cell) const
317 {
318         int x2 = x + tabular.getWidthOfColumn(cell);
319         bool on_off = false;
320
321         if (!tabular.topAlreadyDrawn(cell)) {
322                 on_off = !tabular.topLine(cell);
323                 pain.line(x, y - tabular.getAscentOfRow(row),
324                           x2, y -  tabular.getAscentOfRow(row),
325                           on_off ? LColor::tabularonoffline : LColor::tabularline,
326                           on_off ? Painter::line_onoffdash : Painter::line_solid);
327         }
328         on_off = !tabular.bottomLine(cell);
329         pain.line(x, y + tabular.getDescentOfRow(row),
330                   x2, y + tabular.getDescentOfRow(row),
331                   on_off ? LColor::tabularonoffline : LColor::tabularline,
332                   on_off ? Painter::line_onoffdash : Painter::line_solid);
333         if (!tabular.leftAlreadyDrawn(cell)) {
334                 on_off = !tabular.leftLine(cell);
335                 pain.line(x, y -  tabular.getAscentOfRow(row),
336                           x, y +  tabular.getDescentOfRow(row),
337                           on_off ? LColor::tabularonoffline : LColor::tabularline,
338                           on_off ? Painter::line_onoffdash : Painter::line_solid);
339         }
340         on_off = !tabular.rightLine(cell);
341         pain.line(x2 - tabular.getAdditionalWidth(cell),
342                   y -  tabular.getAscentOfRow(row),
343                   x2 - tabular.getAdditionalWidth(cell),
344                   y +  tabular.getDescentOfRow(row),
345                   on_off ? LColor::tabularonoffline : LColor::tabularline,
346                   on_off ? Painter::line_onoffdash : Painter::line_solid);
347 }
348
349
350 void InsetTabular::drawCellSelection(PainterInfo & pi, int x, int y,
351                                      int row, int column, int cell) const
352 {
353         LCursor & cur = pi.base.bv->cursor();
354         BOOST_ASSERT(cur.selection());
355         if (tablemode(cur)) {
356                 int rs, re, cs, ce;
357                 getSelection(cur, rs, re, cs, ce);
358                 if (column >= cs && column <= ce && row >= rs && row <= re) {
359                         int w = tabular.getWidthOfColumn(cell);
360                         int h = tabular.getAscentOfRow(row) + tabular.getDescentOfRow(row)-1;
361                         pi.pain.fillRectangle(x, y - tabular.getAscentOfRow(row) + 1,
362                                                  w, h, LColor::selection);
363                 }
364         }
365 }
366
367
368 string const InsetTabular::editMessage() const
369 {
370         return _("Opened table");
371 }
372
373
374 void InsetTabular::edit(LCursor & cur, bool left)
375 {
376         lyxerr << "InsetTabular::edit: " << this << endl;
377         finishUndo();
378         int cell;
379         cur.push(*this);
380         if (left) {
381                 if (isRightToLeft(cur))
382                         cell = tabular.getLastCellInRow(0);
383                 else
384                         cell = 0;
385         } else {
386                 if (isRightToLeft(cur))
387                         cell = tabular.getFirstCellInRow(tabular.rows()-1);
388                 else
389                         cell = tabular.getNumberOfCells() - 1;
390         }
391         cur.selection() = false;
392         // this accesses the position cache before it is initialized
393         //resetPos(cur);
394         //cur.bv().fitCursor();
395         cur.idx() = cell;
396 }
397
398
399 InsetBase * InsetTabular::editXY(LCursor & cur, int x, int y) const
400 {
401         //lyxerr << "InsetTabular::editXY: " << this << endl;
402         cur.selection() = false;
403         cur.push(const_cast<InsetTabular&>(*this));
404         return setPos(cur, x, y);
405         //int xx = cursorx_ - xo() + tabular.getBeginningOfTextInCell(cur.idx());
406 }
407
408
409 void InsetTabular::priv_dispatch(LCursor & cur, FuncRequest & cmd)
410 {
411         lyxerr << "# InsetTabular::dispatch: cmd: " << cmd << endl;
412         //lyxerr << "  cur:\n" << cur << endl;
413         CursorSlice sl = cur.top();
414         LCursor & bvcur = cur.bv().cursor();
415
416         switch (cmd.action) {
417
418         case LFUN_MOUSE_PRESS:
419                 lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
420
421                 if (cmd.button() == mouse_button::button1) {
422                         cur.selection() = false;
423                         setPos(cur, cmd.x, cmd.y);
424                         cur.resetAnchor();
425                         bvcur = cur;
426                         break;
427                 }
428
429                 //if (cmd.button() == mouse_button::button2)
430                 //      dispatch(cur, FuncRequest(LFUN_PASTESELECTION, "paragraph"));
431
432                 // we'll pop up the table dialog on release
433                 if (cmd.button() == mouse_button::button3)
434                         break;
435                 break;
436
437         case LFUN_MOUSE_MOTION:
438                 lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
439                 if (cmd.button() == mouse_button::button1) {
440                         // only accept motions to places not deeper nested than the real anchor
441                         if (bvcur.anchor_.hasPart(cur)) {
442                                 setPos(cur, cmd.x, cmd.y);
443                                 bvcur.setCursor(cur);
444                                 bvcur.selection() = true;
445                         }
446                 }
447                 break;
448
449         case LFUN_MOUSE_RELEASE:
450                 lyxerr << "# InsetTabular::MouseRelease\n" << bvcur << endl;
451                 if (cmd.button() == mouse_button::button3)
452                         InsetTabularMailer(*this).showDialog(&cur.bv());
453                 break;
454
455         case LFUN_CELL_BACKWARD:
456                 movePrevCell(cur);
457                 cur.selection() = false;
458                 break;
459
460         case LFUN_CELL_FORWARD:
461                 moveNextCell(cur);
462                 cur.selection() = false;
463                 break;
464
465         case LFUN_SCROLL_INSET:
466                 if (cmd.argument.empty())
467                         break;
468                 if (cmd.argument.find('.') != cmd.argument.npos)
469                         scroll(cur.bv(), static_cast<float>(strToDbl(cmd.argument)));
470                 else
471                         scroll(cur.bv(), strToInt(cmd.argument));
472                 break;
473
474         case LFUN_RIGHTSEL:
475         case LFUN_RIGHT:
476                 cell(cur.idx()).dispatch(cur, cmd);
477                 cur.dispatched(); // override the cell's decision
478                 if (sl == cur.top())
479                         isRightToLeft(cur) ? movePrevCell(cur) : moveNextCell(cur);
480                 if (sl == cur.top()) {
481                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
482                         cur.undispatched();
483                 }
484                 break;
485
486         case LFUN_LEFTSEL:
487         case LFUN_LEFT:
488                 cell(cur.idx()).dispatch(cur, cmd);
489                 cur.dispatched(); // override the cell's decision
490                 if (sl == cur.top())
491                         isRightToLeft(cur) ? moveNextCell(cur) : movePrevCell(cur);
492                 if (sl == cur.top()) {
493                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
494                         cur.undispatched();
495                 }
496                 break;
497
498         case LFUN_DOWNSEL:
499         case LFUN_DOWN:
500                 cell(cur.idx()).dispatch(cur, cmd);
501                 cur.dispatched(); // override the cell's decision
502                 if (sl == cur.top())
503                         if (tabular.row_of_cell(cur.idx()) != tabular.rows() - 1) {
504                                 cur.idx() = tabular.getCellBelow(cur.idx());
505                                 cur.par() = 0;
506                                 cur.pos() = 0;
507                                 resetPos(cur);
508                         }
509                 if (sl == cur.top()) {
510                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
511                         cur.undispatched();
512                 }
513                 break;
514
515         case LFUN_UPSEL:
516         case LFUN_UP:
517                 cell(cur.idx()).dispatch(cur, cmd);
518                 cur.dispatched(); // override the cell's decision
519                 if (sl == cur.top())
520                         if (tabular.row_of_cell(cur.idx()) != 0) {
521                                 cur.idx() = tabular.getCellAbove(cur.idx());
522                                 cur.par() = cur.lastpar();
523                                 cur.pos() = cur.lastpos();
524                                 resetPos(cur);
525                         }
526                 if (sl == cur.top()) {
527                         cmd = FuncRequest(LFUN_FINISHED_UP);
528                         cur.undispatched();
529                 }
530                 break;
531
532         case LFUN_NEXT: {
533                 //if (hasSelection())
534                 //      cur.selection() = false;
535                 int const col = tabular.column_of_cell(cur.idx());
536                 if (cur.bv().top_y() + cur.bv().painter().paperHeight()
537                                 < yo() + tabular.getHeightOfTabular())
538                 {
539                         cur.bv().scrollDocView(
540                                 cur.bv().top_y() + cur.bv().painter().paperHeight());
541                         cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
542                 } else {
543                         cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
544                 }
545                 resetPos(cur);
546                 break;
547         }
548
549         case LFUN_PRIOR: {
550                 //if (hasSelection())
551                 //      cur.selection() = false;
552                 int const col = tabular.column_of_cell(cur.idx());
553                 if (yo() < 0) {
554                         cur.bv().scrollDocView(
555                                 cur.bv().top_y() - cur.bv().painter().paperHeight());
556                         if (yo() > 0)
557                                 cur.idx() = col;
558                         else
559                                 cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
560                 } else {
561                         cur.idx() = col;
562                 }
563                 resetPos(cur);
564                 break;
565         }
566
567         case LFUN_LAYOUT_TABULAR:
568                 InsetTabularMailer(*this).showDialog(&cur.bv());
569                 break;
570
571         case LFUN_INSET_DIALOG_UPDATE:
572                 InsetTabularMailer(*this).updateDialog(&cur.bv());
573                 break;
574
575         case LFUN_TABULAR_FEATURE:
576                 if (!tabularFeatures(cur, cmd.argument))
577                         cur.undispatched();
578                 break;
579
580         // insert file functions
581         case LFUN_FILE_INSERT_ASCII_PARA:
582         case LFUN_FILE_INSERT_ASCII: {
583                 string tmpstr = getContentsOfAsciiFile(&cur.bv(), cmd.argument, false);
584                 if (!tmpstr.empty() && !insertAsciiString(cur.bv(), tmpstr, false))
585                         cur.undispatched();
586                 break;
587         }
588
589         case LFUN_CUT:
590                 if (copySelection(cur)) {
591                         recordUndo(cur, Undo::DELETE);
592                         cutSelection(cur);
593                 }
594                 break;
595
596         case LFUN_BACKSPACE:
597         case LFUN_DELETE:
598                 recordUndo(cur, Undo::DELETE);
599                 if (tablemode(cur))
600                         cutSelection(cur);
601                 else
602                         cell(cur.idx()).dispatch(cur, cmd);
603                 break;
604
605         case LFUN_COPY:
606                 if (!cur.selection())
607                         break;
608                 finishUndo();
609                 copySelection(cur);
610                 break;
611
612         case LFUN_PASTESELECTION: {
613                 string const clip = cur.bv().getClipboard();
614                 if (clip.empty())
615                         break;
616                 if (clip.find('\t') != string::npos) {
617                         int cols = 1;
618                         int rows = 1;
619                         int maxCols = 1;
620                         size_t len = clip.length();
621                         for (size_t p = 0; p < len; ++p) {
622                                 p = clip.find_first_of("\t\n", p);
623                                 if (p == string::npos)
624                                         break;
625                                 switch (clip[p]) {
626                                 case '\t':
627                                         ++cols;
628                                         break;
629                                 case '\n':
630                                         if (p + 1 < len)
631                                                 ++rows;
632                                         maxCols = max(cols, maxCols);
633                                         cols = 1;
634                                         break;
635                                 }
636                         }
637                         maxCols = max(cols, maxCols);
638
639                         paste_tabular.reset(
640                                 new LyXTabular(cur.buffer().params(), rows, maxCols));
641
642                         string::size_type op = 0;
643                         int cell = 0;
644                         int cells = paste_tabular->getNumberOfCells();
645                         cols = 0;
646                         LyXFont font;
647                         for (size_t p = 0; cell < cells && p < len; ++p) {
648                                 p = clip.find_first_of("\t\n", p);
649                                 if (p == string::npos || p >= len)
650                                         break;
651                                 switch (clip[p]) {
652                                 case '\t':
653                                         paste_tabular->getCellInset(cell).
654                                                 setText(clip.substr(op, p - op), font);
655                                         ++cols;
656                                         ++cell;
657                                         break;
658                                 case '\n':
659                                         paste_tabular->getCellInset(cell).
660                                                 setText(clip.substr(op, p - op), font);
661                                         while (cols++ < maxCols)
662                                                 ++cell;
663                                         cols = 0;
664                                         break;
665                                 }
666                                 op = p + 1;
667                         }
668                         // check for the last cell if there is no trailing '\n'
669                         if (cell < cells && op < len)
670                                 paste_tabular->getCellInset(cell).
671                                         setText(clip.substr(op, len - op), font);
672                 } else if (!insertAsciiString(cur.bv(), clip, true)) {
673                         // so that the clipboard is used and it goes on
674                         // to default
675                         // and executes LFUN_PASTESELECTION in insettext!
676                         paste_tabular.reset();
677                 }
678                 // fall through
679         }
680
681         case LFUN_PASTE:
682                 if (hasPasteBuffer()) {
683                         recordUndo(cur, Undo::INSERT);
684                         pasteSelection(cur);
685                         break;
686                 }
687                 cell(cur.idx()).dispatch(cur, cmd);
688                 break;
689
690         default:
691                 // we try to handle this event in the insets dispatch function.
692                 cell(cur.idx()).dispatch(cur, cmd);
693                 break;
694         }
695
696         InsetTabularMailer(*this).updateDialog(&cur.bv());
697 }
698
699
700 // function sets an object as defined in func_status.h:
701 // states OK, Unknown, Disabled, On, Off.
702 bool InsetTabular::getStatus(LCursor & cur, FuncRequest const & cmd,
703         FuncStatus & status) const
704 {
705         switch (cmd.action) {
706         case LFUN_TABULAR_FEATURE: {
707                 int action = LyXTabular::LAST_ACTION;
708                 int i = 0;
709                 for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
710                         string const tmp = tabularFeature[i].feature;
711                         if (tmp == cmd.argument.substr(0, tmp.length())) {
712                                 action = tabularFeature[i].action;
713                                 break;
714                         }
715                 }
716                 if (action == LyXTabular::LAST_ACTION) {
717                         status.clear();
718                         status.unknown(true);
719                         return true;
720                 }
721
722                 string const argument
723                         = ltrim(cmd.argument.substr(tabularFeature[i].feature.length()));
724
725                 int sel_row_start = 0;
726                 int sel_row_end = 0;
727                 int dummy;
728                 LyXTabular::ltType dummyltt;
729                 bool flag = true;
730
731                 getSelection(cur, sel_row_start, sel_row_end, dummy, dummy);
732
733                 switch (action) {
734                 case LyXTabular::SET_PWIDTH:
735                 case LyXTabular::SET_MPWIDTH:
736                 case LyXTabular::SET_SPECIAL_COLUMN:
737                 case LyXTabular::SET_SPECIAL_MULTI:
738                 case LyXTabular::APPEND_ROW:
739                 case LyXTabular::APPEND_COLUMN:
740                 case LyXTabular::DELETE_ROW:
741                 case LyXTabular::DELETE_COLUMN:
742                 case LyXTabular::SET_ALL_LINES:
743                 case LyXTabular::UNSET_ALL_LINES:
744                         status.clear();
745                         return true;
746
747                 case LyXTabular::MULTICOLUMN:
748                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
749                         break;
750
751                 case LyXTabular::M_TOGGLE_LINE_TOP:
752                         flag = false;
753                 case LyXTabular::TOGGLE_LINE_TOP:
754                         status.setOnOff(tabular.topLine(cur.idx(), flag));
755                         break;
756
757                 case LyXTabular::M_TOGGLE_LINE_BOTTOM:
758                         flag = false;
759                 case LyXTabular::TOGGLE_LINE_BOTTOM:
760                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
761                         break;
762
763                 case LyXTabular::M_TOGGLE_LINE_LEFT:
764                         flag = false;
765                 case LyXTabular::TOGGLE_LINE_LEFT:
766                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
767                         break;
768
769                 case LyXTabular::M_TOGGLE_LINE_RIGHT:
770                         flag = false;
771                 case LyXTabular::TOGGLE_LINE_RIGHT:
772                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
773                         break;
774
775                 case LyXTabular::M_ALIGN_LEFT:
776                         flag = false;
777                 case LyXTabular::ALIGN_LEFT:
778                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
779                         break;
780
781                 case LyXTabular::M_ALIGN_RIGHT:
782                         flag = false;
783                 case LyXTabular::ALIGN_RIGHT:
784                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
785                         break;
786
787                 case LyXTabular::M_ALIGN_CENTER:
788                         flag = false;
789                 case LyXTabular::ALIGN_CENTER:
790                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
791                         break;
792
793                 case LyXTabular::ALIGN_BLOCK:
794                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
795                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
796                         break;
797
798                 case LyXTabular::M_VALIGN_TOP:
799                         flag = false;
800                 case LyXTabular::VALIGN_TOP:
801                         status.setOnOff(
802                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_TOP);
803                         break;
804
805                 case LyXTabular::M_VALIGN_BOTTOM:
806                         flag = false;
807                 case LyXTabular::VALIGN_BOTTOM:
808                         status.setOnOff(
809                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_BOTTOM);
810                         break;
811
812                 case LyXTabular::M_VALIGN_MIDDLE:
813                         flag = false;
814                 case LyXTabular::VALIGN_MIDDLE:
815                         status.setOnOff(
816                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_MIDDLE);
817                         break;
818
819                 case LyXTabular::SET_LONGTABULAR:
820                         status.setOnOff(tabular.isLongTabular());
821                         break;
822
823                 case LyXTabular::UNSET_LONGTABULAR:
824                         status.setOnOff(!tabular.isLongTabular());
825                         break;
826
827                 case LyXTabular::SET_ROTATE_TABULAR:
828                         status.setOnOff(tabular.getRotateTabular());
829                         break;
830
831                 case LyXTabular::UNSET_ROTATE_TABULAR:
832                         status.setOnOff(!tabular.getRotateTabular());
833                         break;
834
835                 case LyXTabular::SET_ROTATE_CELL:
836                         status.setOnOff(tabular.getRotateCell(cur.idx()));
837                         break;
838
839                 case LyXTabular::UNSET_ROTATE_CELL:
840                         status.setOnOff(!tabular.getRotateCell(cur.idx()));
841                         break;
842
843                 case LyXTabular::SET_USEBOX:
844                         status.setOnOff(strToInt(argument) == tabular.getUsebox(cur.idx()));
845                         break;
846
847                 case LyXTabular::SET_LTFIRSTHEAD:
848                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
849                         break;
850
851                 case LyXTabular::SET_LTHEAD:
852                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
853                         break;
854
855                 case LyXTabular::SET_LTFOOT:
856                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
857                         break;
858
859                 case LyXTabular::SET_LTLASTFOOT:
860                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
861                         break;
862
863                 case LyXTabular::SET_LTNEWPAGE:
864                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
865                         break;
866
867                 default:
868                         status.clear();
869                         status.enabled(false);
870                         break;
871                 }
872                 return true;
873         }
874
875         default:
876                 // we try to handle this event in the insets dispatch function.
877                 return cell(cur.idx()).getStatus(cur, cmd, status);
878         }
879 }
880
881
882 int InsetTabular::latex(Buffer const & buf, ostream & os,
883                         OutputParams const & runparams) const
884 {
885         return tabular.latex(buf, os, runparams);
886 }
887
888
889 int InsetTabular::plaintext(Buffer const & buf, ostream & os,
890                         OutputParams const & runparams) const
891 {
892         int dp = runparams.linelen ? runparams.depth : 0;
893         return tabular.plaintext(buf, os, runparams, dp, false, 0);
894 }
895
896
897 int InsetTabular::linuxdoc(Buffer const & buf, ostream & os,
898                            OutputParams const & runparams) const
899 {
900         return tabular.linuxdoc(buf,os, runparams);
901 }
902
903
904 int InsetTabular::docbook(Buffer const & buf, ostream & os,
905                           OutputParams const & runparams) const
906 {
907         int ret = 0;
908         InsetOld * master = 0;
909
910 #ifdef WITH_WARNINGS
911 #warning Why not pass a proper DocIterator here?
912 #endif
913 #if 0
914         // if the table is inside a float it doesn't need the informaltable
915         // wrapper. Search for it.
916         for (master = owner(); master; master = master->owner())
917                 if (master->lyxCode() == InsetOld::FLOAT_CODE)
918                         break;
919 #endif
920
921         if (!master) {
922                 os << "<informaltable>";
923                 if (runparams.mixed_content)
924                         os << endl;
925                 ++ret;
926         }
927         ret += tabular.docbook(buf, os, runparams);
928         if (!master) {
929                 os << "</informaltable>";
930                 if (runparams.mixed_content)
931                         os << endl;
932                 ++ret;
933         }
934         return ret;
935 }
936
937
938 void InsetTabular::validate(LaTeXFeatures & features) const
939 {
940         tabular.validate(features);
941 }
942
943
944 InsetText const & InsetTabular::cell(int idx) const
945 {
946         return tabular.getCellInset(idx);
947 }
948
949
950 InsetText & InsetTabular::cell(int idx)
951 {
952         return tabular.getCellInset(idx);
953 }
954
955
956 void InsetTabular::getCursorPos(LCursor const & cur, int & x, int & y) const
957 {
958         cell(cur.idx()).getCursorPos(cur, x, y);
959 }
960
961
962 InsetBase * InsetTabular::setPos(LCursor & cur, int x, int y) const
963 {
964         lyxerr << "# InsetTabular::setPos()  x=" << x << " y=" << y << endl;
965         int idx_min = 0;
966         int dist_min = 1000000;
967         for (idx_type i = 0; i < nargs(); ++i) {
968                 int d = getText(i)->dist(x, y);
969                 if (d < dist_min) {
970                         dist_min = d;
971                         idx_min = i;
972                 }
973         }
974         cur.idx() = idx_min;
975         InsetBase * inset = cell(cur.idx()).text_.editXY(cur, x, y);
976         //lyxerr << "# InsetTabular::setPos()\n" << cur << endl;
977         return inset;
978 }
979
980
981 int InsetTabular::getCellXPos(int cell) const
982 {
983         int c = cell;
984
985         for (; !tabular.isFirstCellInRow(c); --c)
986                 ;
987         int lx = tabular.getWidthOfColumn(cell);
988         for (; c < cell; ++c)
989                 lx += tabular.getWidthOfColumn(c);
990
991         return lx - tabular.getWidthOfColumn(cell) + xo();
992 }
993
994
995 void InsetTabular::resetPos(LCursor & cur) const
996 {
997         BufferView & bv = cur.bv();
998         int const actcol = tabular.column_of_cell(cur.idx());
999         int const offset = ADD_TO_TABULAR_WIDTH + 2;
1000         int const new_x = getCellXPos(cur.idx()) + offset;
1001         int const old_x = cursorx_;
1002         int const col_width = tabular.getWidthOfColumn(cur.idx());
1003         cursorx_ = new_x;
1004 //    cursor.x(getCellXPos(cur.idx()) + offset);
1005         if (actcol < tabular.columns() - 1 && scroll(false) &&
1006                 tabular.getWidthOfTabular() < bv.workWidth()-20)
1007         {
1008                 scroll(bv, 0.0F);
1009         } else if (cursorx_ - offset > 20 &&
1010                    cursorx_ - offset + col_width > bv.workWidth() - 20) {
1011                 scroll(bv, - col_width - 20);
1012         } else if (cursorx_ - offset < 20) {
1013                 scroll(bv, 20 - cursorx_ + offset);
1014         } else if (scroll() && xo() > 20 &&
1015                    xo() + tabular.getWidthOfTabular() > bv.workWidth() - 20) {
1016                 scroll(bv, old_x - cursorx_);
1017         }
1018
1019         InsetTabularMailer(*this).updateDialog(&bv);
1020 }
1021
1022
1023 void InsetTabular::moveNextCell(LCursor & cur)
1024 {
1025         lyxerr << "InsetTabular::moveNextCell 1 cur: " << cur.top() << endl;
1026         if (isRightToLeft(cur)) {
1027                 lyxerr << "InsetTabular::moveNextCell A cur: " << endl;
1028                 if (tabular.isFirstCellInRow(cur.idx())) {
1029                         int row = tabular.row_of_cell(cur.idx());
1030                         if (row == tabular.rows() - 1)
1031                                 return;
1032                         cur.idx() = tabular.getLastCellInRow(row);
1033                         cur.idx() = tabular.getCellBelow(cur.idx());
1034                 } else {
1035                         if (cur.idx() == 0)
1036                                 return;
1037                         --cur.idx();
1038                 }
1039         } else {
1040                 lyxerr << "InsetTabular::moveNextCell B cur: " << endl;
1041                 if (tabular.isLastCell(cur.idx()))
1042                         return;
1043                 ++cur.idx();
1044         }
1045         cur.par() = 0;
1046         cur.pos() = 0;
1047         lyxerr << "InsetTabular::moveNextCell 2 cur: " << cur.top() << endl;
1048         resetPos(cur);
1049 }
1050
1051
1052 void InsetTabular::movePrevCell(LCursor & cur)
1053 {
1054         if (isRightToLeft(cur)) {
1055                 if (tabular.isLastCellInRow(cur.idx())) {
1056                         int row = tabular.row_of_cell(cur.idx());
1057                         if (row == 0)
1058                                 return;
1059                         cur.idx() = tabular.getFirstCellInRow(row);
1060                         cur.idx() = tabular.getCellAbove(cur.idx());
1061                 } else {
1062                         if (tabular.isLastCell(cur.idx()))
1063                                 return;
1064                         ++cur.idx();
1065                 }
1066         } else {
1067                 if (cur.idx() == 0) // first cell
1068                         return;
1069                 --cur.idx();
1070         }
1071         cur.par() = 0;
1072         cur.pos() = 0;
1073         resetPos(cur);
1074 }
1075
1076
1077 bool InsetTabular::tabularFeatures(LCursor & cur, string const & what)
1078 {
1079         LyXTabular::Feature action = LyXTabular::LAST_ACTION;
1080
1081         int i = 0;
1082         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
1083                 string const tmp = tabularFeature[i].feature;
1084
1085                 if (tmp == what.substr(0, tmp.length())) {
1086                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
1087                         //tabularFeatures[i].feature.length())) {
1088                         action = tabularFeature[i].action;
1089                         break;
1090                 }
1091         }
1092         if (action == LyXTabular::LAST_ACTION)
1093                 return false;
1094
1095         string const val =
1096                 ltrim(what.substr(tabularFeature[i].feature.length()));
1097         tabularFeatures(cur, action, val);
1098         return true;
1099 }
1100
1101
1102 namespace {
1103
1104 void checkLongtableSpecial(LyXTabular::ltType & ltt,
1105                           string const & special, bool & flag)
1106 {
1107         if (special == "dl_above") {
1108                 ltt.topDL = flag;
1109                 ltt.set = false;
1110         } else if (special == "dl_below") {
1111                 ltt.bottomDL = flag;
1112                 ltt.set = false;
1113         } else if (special == "empty") {
1114                 ltt.empty = flag;
1115                 ltt.set = false;
1116         } else if (flag) {
1117                 ltt.empty = false;
1118                 ltt.set = true;
1119         }
1120 }
1121
1122 } // anon namespace
1123
1124
1125 void InsetTabular::tabularFeatures(LCursor & cur,
1126         LyXTabular::Feature feature, string const & value)
1127 {
1128         BufferView & bv = cur.bv();
1129         int sel_col_start;
1130         int sel_col_end;
1131         int sel_row_start;
1132         int sel_row_end;
1133         bool setLines = false;
1134         LyXAlignment setAlign = LYX_ALIGN_LEFT;
1135         LyXTabular::VAlignment setVAlign = LyXTabular::LYX_VALIGN_TOP;
1136
1137         switch (feature) {
1138
1139         case LyXTabular::M_ALIGN_LEFT:
1140         case LyXTabular::ALIGN_LEFT:
1141                 setAlign = LYX_ALIGN_LEFT;
1142                 break;
1143
1144         case LyXTabular::M_ALIGN_RIGHT:
1145         case LyXTabular::ALIGN_RIGHT:
1146                 setAlign = LYX_ALIGN_RIGHT;
1147                 break;
1148
1149         case LyXTabular::M_ALIGN_CENTER:
1150         case LyXTabular::ALIGN_CENTER:
1151                 setAlign = LYX_ALIGN_CENTER;
1152                 break;
1153
1154         case LyXTabular::ALIGN_BLOCK:
1155                 setAlign = LYX_ALIGN_BLOCK;
1156                 break;
1157
1158         case LyXTabular::M_VALIGN_TOP:
1159         case LyXTabular::VALIGN_TOP:
1160                 setVAlign = LyXTabular::LYX_VALIGN_TOP;
1161                 break;
1162
1163         case LyXTabular::M_VALIGN_BOTTOM:
1164         case LyXTabular::VALIGN_BOTTOM:
1165                 setVAlign = LyXTabular::LYX_VALIGN_BOTTOM;
1166                 break;
1167
1168         case LyXTabular::M_VALIGN_MIDDLE:
1169         case LyXTabular::VALIGN_MIDDLE:
1170                 setVAlign = LyXTabular::LYX_VALIGN_MIDDLE;
1171                 break;
1172
1173         default:
1174                 break;
1175         }
1176
1177         recordUndo(cur, Undo::ATOMIC);
1178
1179         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1180         int row = tabular.row_of_cell(cur.idx());
1181         int column = tabular.column_of_cell(cur.idx());
1182         bool flag = true;
1183         LyXTabular::ltType ltt;
1184
1185         switch (feature) {
1186
1187         case LyXTabular::SET_PWIDTH: {
1188                 LyXLength const len(value);
1189                 tabular.setColumnPWidth(cur.idx(), len);
1190                 if (len.zero()
1191                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
1192                         tabularFeatures(cur, LyXTabular::ALIGN_CENTER, string());
1193                 else if (!len.zero()
1194                          && tabular.getAlignment(cur.idx(), true) != LYX_ALIGN_BLOCK)
1195                         tabularFeatures(cur, LyXTabular::ALIGN_BLOCK, string());
1196                 break;
1197         }
1198
1199         case LyXTabular::SET_MPWIDTH:
1200                 tabular.setMColumnPWidth(cur.idx(), LyXLength(value));
1201                 break;
1202
1203         case LyXTabular::SET_SPECIAL_COLUMN:
1204         case LyXTabular::SET_SPECIAL_MULTI:
1205                 tabular.setAlignSpecial(cur.idx(),value,feature);
1206                 break;
1207
1208         case LyXTabular::APPEND_ROW:
1209                 // append the row into the tabular
1210                 tabular.appendRow(bv.buffer()->params(), cur.idx());
1211                 break;
1212
1213         case LyXTabular::APPEND_COLUMN:
1214                 // append the column into the tabular
1215                 tabular.appendColumn(bv.buffer()->params(), cur.idx());
1216                 cur.idx() = tabular.getCellNumber(row, column);
1217                 break;
1218
1219         case LyXTabular::DELETE_ROW:
1220                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1221                         tabular.deleteRow(sel_row_start);
1222                 if (sel_row_start >= tabular.rows())
1223                         --sel_row_start;
1224                 cur.idx() = tabular.getCellNumber(sel_row_start, column);
1225                 cur.pos() = 0;
1226                 cur.selection() = false;
1227                 break;
1228
1229         case LyXTabular::DELETE_COLUMN:
1230                 for (int i = sel_col_start; i <= sel_col_end; ++i)
1231                         tabular.deleteColumn(sel_col_start);
1232                 if (sel_col_start >= tabular.columns())
1233                         --sel_col_start;
1234                 cur.idx() = tabular.getCellNumber(row, sel_col_start);
1235                 cur.pos() = 0;
1236                 cur.selection() = false;
1237                 break;
1238
1239         case LyXTabular::M_TOGGLE_LINE_TOP:
1240                 flag = false;
1241         case LyXTabular::TOGGLE_LINE_TOP: {
1242                 bool lineSet = !tabular.topLine(cur.idx(), flag);
1243                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1244                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1245                                 tabular.setTopLine(
1246                                         tabular.getCellNumber(i, j),
1247                                         lineSet, flag);
1248                 break;
1249         }
1250
1251         case LyXTabular::M_TOGGLE_LINE_BOTTOM:
1252                 flag = false;
1253         case LyXTabular::TOGGLE_LINE_BOTTOM: {
1254                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
1255                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1256                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1257                                 tabular.setBottomLine(
1258                                         tabular.getCellNumber(i, j),
1259                                         lineSet,
1260                                         flag);
1261                 break;
1262         }
1263
1264         case LyXTabular::M_TOGGLE_LINE_LEFT:
1265                 flag = false;
1266         case LyXTabular::TOGGLE_LINE_LEFT: {
1267                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
1268                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1269                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1270                                 tabular.setLeftLine(
1271                                         tabular.getCellNumber(i,j),
1272                                         lineSet,
1273                                         flag);
1274                 break;
1275         }
1276
1277         case LyXTabular::M_TOGGLE_LINE_RIGHT:
1278                 flag = false;
1279         case LyXTabular::TOGGLE_LINE_RIGHT: {
1280                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
1281                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1282                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1283                                 tabular.setRightLine(
1284                                         tabular.getCellNumber(i,j),
1285                                         lineSet,
1286                                         flag);
1287                 break;
1288         }
1289
1290         case LyXTabular::M_ALIGN_LEFT:
1291         case LyXTabular::M_ALIGN_RIGHT:
1292         case LyXTabular::M_ALIGN_CENTER:
1293                 flag = false;
1294         case LyXTabular::ALIGN_LEFT:
1295         case LyXTabular::ALIGN_RIGHT:
1296         case LyXTabular::ALIGN_CENTER:
1297         case LyXTabular::ALIGN_BLOCK:
1298                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1299                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1300                                 tabular.setAlignment(
1301                                         tabular.getCellNumber(i, j),
1302                                         setAlign,
1303                                         flag);
1304                 break;
1305
1306         case LyXTabular::M_VALIGN_TOP:
1307         case LyXTabular::M_VALIGN_BOTTOM:
1308         case LyXTabular::M_VALIGN_MIDDLE:
1309                 flag = false;
1310         case LyXTabular::VALIGN_TOP:
1311         case LyXTabular::VALIGN_BOTTOM:
1312         case LyXTabular::VALIGN_MIDDLE:
1313                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1314                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1315                                 tabular.setVAlignment(
1316                                         tabular.getCellNumber(i, j),
1317                                         setVAlign, flag);
1318                 break;
1319
1320         case LyXTabular::MULTICOLUMN: {
1321                 if (sel_row_start != sel_row_end) {
1322 #ifdef WITH_WARNINGS
1323 #warning Need I say it ? This is horrible.
1324 #endif
1325                         Alert::error(_("Error setting multicolumn"),
1326                                    _("You cannot set multicolumn vertically."));
1327                         return;
1328                 }
1329 #if 0
1330                 // just multicol for one Single Cell
1331                 if (!hasSelection()) {
1332                         // check whether we are completly in a multicol
1333                         if (tabular.isMultiColumn(cur.idx()))
1334                                 tabular.unsetMultiColumn(cur.idx());
1335                         else
1336                                 tabular.setMultiColumn(bv.buffer(), cur.idx(), 1);
1337                         break;
1338                 }
1339                 // we have a selection so this means we just add all this
1340                 // cells to form a multicolumn cell
1341                 int s_start;
1342                 int s_end;
1343
1344                 if (sel_cell_start > sel_cell_end) {
1345                         s_start = sel_cell_end;
1346                         s_end = sel_cell_start;
1347                 } else {
1348                         s_start = sel_cell_start;
1349                         s_end = sel_cell_end;
1350                 }
1351                 tabular.setMultiColumn(bv.buffer(), s_start, s_end - s_start + 1);
1352                 cur.idx() = s_start;
1353 #endif
1354                 cur.selection() = false;
1355                 break;
1356         }
1357
1358         case LyXTabular::SET_ALL_LINES:
1359                 setLines = true;
1360         case LyXTabular::UNSET_ALL_LINES:
1361 #if 0
1362                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1363                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1364                                 tabular.setAllLines(
1365                                         tabular.getCellNumber(i,j), setLines);
1366 #endif
1367                 break;
1368
1369         case LyXTabular::SET_LONGTABULAR:
1370                 tabular.setLongTabular(true);
1371                 break;
1372
1373         case LyXTabular::UNSET_LONGTABULAR:
1374                 tabular.setLongTabular(false);
1375                 break;
1376
1377         case LyXTabular::SET_ROTATE_TABULAR:
1378                 tabular.setRotateTabular(true);
1379                 break;
1380
1381         case LyXTabular::UNSET_ROTATE_TABULAR:
1382                 tabular.setRotateTabular(false);
1383                 break;
1384
1385         case LyXTabular::SET_ROTATE_CELL:
1386                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1387                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1388                                 tabular.setRotateCell(
1389                                         tabular.getCellNumber(i, j), true);
1390                 break;
1391
1392         case LyXTabular::UNSET_ROTATE_CELL:
1393                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1394                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1395                                 tabular.setRotateCell(
1396                                         tabular.getCellNumber(i, j), false);
1397                 break;
1398
1399         case LyXTabular::SET_USEBOX: {
1400                 LyXTabular::BoxType val = LyXTabular::BoxType(strToInt(value));
1401                 if (val == tabular.getUsebox(cur.idx()))
1402                         val = LyXTabular::BOX_NONE;
1403                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1404                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1405                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1406                 break;
1407         }
1408
1409         case LyXTabular::UNSET_LTFIRSTHEAD:
1410                 flag = false;
1411         case LyXTabular::SET_LTFIRSTHEAD:
1412                 tabular.getRowOfLTFirstHead(row, ltt);
1413                 checkLongtableSpecial(ltt, value, flag);
1414                 tabular.setLTHead(row, flag, ltt, true);
1415                 break;
1416
1417         case LyXTabular::UNSET_LTHEAD:
1418                 flag = false;
1419         case LyXTabular::SET_LTHEAD:
1420                 tabular.getRowOfLTHead(row, ltt);
1421                 checkLongtableSpecial(ltt, value, flag);
1422                 tabular.setLTHead(row, flag, ltt, false);
1423                 break;
1424
1425         case LyXTabular::UNSET_LTFOOT:
1426                 flag = false;
1427         case LyXTabular::SET_LTFOOT:
1428                 tabular.getRowOfLTFoot(row, ltt);
1429                 checkLongtableSpecial(ltt, value, flag);
1430                 tabular.setLTFoot(row, flag, ltt, false);
1431                 break;
1432
1433         case LyXTabular::UNSET_LTLASTFOOT:
1434                 flag = false;
1435         case LyXTabular::SET_LTLASTFOOT:
1436                 tabular.getRowOfLTLastFoot(row, ltt);
1437                 checkLongtableSpecial(ltt, value, flag);
1438                 tabular.setLTFoot(row, flag, ltt, true);
1439                 break;
1440
1441         case LyXTabular::SET_LTNEWPAGE:
1442                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1443                 break;
1444
1445         // dummy stuff just to avoid warnings
1446         case LyXTabular::LAST_ACTION:
1447                 break;
1448         }
1449
1450         InsetTabularMailer(*this).updateDialog(&bv);
1451 }
1452
1453
1454 bool InsetTabular::showInsetDialog(BufferView * bv) const
1455 {
1456         InsetTabularMailer(*this).showDialog(bv);
1457         return true;
1458 }
1459
1460
1461 void InsetTabular::openLayoutDialog(BufferView * bv) const
1462 {
1463         InsetTabularMailer(*this).showDialog(bv);
1464 }
1465
1466
1467 void InsetTabular::getLabelList(Buffer const & buffer,
1468                                 vector<string> & list) const
1469 {
1470         tabular.getLabelList(buffer, list);
1471 }
1472
1473
1474 bool InsetTabular::copySelection(LCursor & cur)
1475 {
1476         if (!cur.selection())
1477                 return false;
1478
1479         int rs, re, cs, ce;
1480         getSelection(cur, rs, re, cs, ce);
1481
1482         paste_tabular.reset(new LyXTabular(tabular));
1483
1484         for (int i = 0; i < rs; ++i)
1485                 paste_tabular->deleteRow(0);
1486
1487         int const rows = re - rs + 1;
1488         while (paste_tabular->rows() > rows)
1489                 paste_tabular->deleteRow(rows);
1490
1491         paste_tabular->setTopLine(0, true, true);
1492         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
1493                                      true, true);
1494
1495         for (int i = 0; i < cs; ++i)
1496                 paste_tabular->deleteColumn(0);
1497
1498         int const columns = ce - cs + 1;
1499         while (paste_tabular->columns() > columns)
1500                 paste_tabular->deleteColumn(columns);
1501
1502         paste_tabular->setLeftLine(0, true, true);
1503         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
1504                                     true, true);
1505
1506         ostringstream os;
1507         OutputParams const runparams;
1508         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
1509         cur.bv().stuffClipboard(os.str());
1510         return true;
1511 }
1512
1513
1514 bool InsetTabular::pasteSelection(LCursor & cur)
1515 {
1516         if (!paste_tabular)
1517                 return false;
1518         int actcol = tabular.column_of_cell(cur.idx());
1519         int actrow = tabular.row_of_cell(cur.idx());
1520         for (int r1 = 0, r2 = actrow;
1521              r1 < paste_tabular->rows() && r2 < tabular.rows();
1522              ++r1, ++r2) {
1523                 for (int c1 = 0, c2 = actcol;
1524                     c1 < paste_tabular->columns() && c2 < tabular.columns();
1525                     ++c1, ++c2) {
1526                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
1527                             tabular.isPartOfMultiColumn(r2, c2))
1528                                 continue;
1529                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
1530                                 --c2;
1531                                 continue;
1532                         }
1533                         if (tabular.isPartOfMultiColumn(r2, c2)) {
1534                                 --c1;
1535                                 continue;
1536                         }
1537                         InsetText & inset = tabular.getCellInset(r2, c2);
1538                         inset = paste_tabular->getCellInset(r1, c1);
1539                         inset.markNew();
1540                 }
1541         }
1542         return true;
1543 }
1544
1545
1546 void InsetTabular::cutSelection(LCursor & cur)
1547 {
1548         if (!cur.selection())
1549                 return;
1550
1551         bool const track = cur.buffer().params().tracking_changes;
1552         int rs, re, cs, ce;
1553         getSelection(cur, rs, re, cs, ce);
1554         for (int i = rs; i <= re; ++i)
1555                 for (int j = cs; j <= ce; ++j)
1556                         cell(tabular.getCellNumber(i, j)).clear(track);
1557
1558         // cursor position might be invalid now
1559         cur.pos() = cur.lastpos();
1560         cur.clearSelection();
1561 }
1562
1563
1564 bool InsetTabular::isRightToLeft(LCursor & cur) const
1565 {
1566         BOOST_ASSERT(cur.size() > 1);
1567         Paragraph const & parentpar = cur[cur.size() - 2].paragraph();
1568         LCursor::pos_type const parentpos = cur[cur.size() - 2].pos();
1569         return parentpar.getFontSettings(cur.bv().buffer()->params(),
1570                                          parentpos).language()->RightToLeft();
1571 }
1572
1573
1574 void InsetTabular::getSelection(LCursor & cur,
1575         int & rs, int & re, int & cs, int & ce) const
1576 {
1577         CursorSlice const & beg = cur.selBegin();
1578         CursorSlice const & end = cur.selEnd();
1579         cs = tabular.column_of_cell(beg.idx());
1580         ce = tabular.column_of_cell(end.idx());
1581         if (cs > ce) {
1582                 ce = cs;
1583                 cs = tabular.column_of_cell(end.idx());
1584         } else {
1585                 ce = tabular.right_column_of_cell(end.idx());
1586         }
1587
1588         rs = tabular.row_of_cell(beg.idx());
1589         re = tabular.row_of_cell(end.idx());
1590         if (rs > re)
1591                 swap(rs, re);
1592 }
1593
1594
1595 size_t InsetTabular::nargs() const
1596 {
1597         return tabular.getNumberOfCells();
1598 }
1599
1600
1601 LyXText * InsetTabular::getText(int idx) const
1602 {
1603         return size_t(idx) < nargs() ? cell(idx).getText(0) : 0;
1604 }
1605
1606
1607 void InsetTabular::markErased()
1608 {
1609         for (idx_type idx = 0; idx < nargs(); ++idx)
1610                 cell(idx).markErased();
1611 }
1612
1613
1614 bool InsetTabular::forceDefaultParagraphs(InsetBase const *) const
1615 {
1616 #if 0
1617         const int cell = tabular.getCellFromInset(in);
1618
1619         if (cell != -1)
1620                 return tabular.getPWidth(cell).zero();
1621
1622         // this is a workaround for a crash (New, Insert->Tabular,
1623         // Insert->FootNote)
1624         if (!owner())
1625                 return false;
1626
1627         // well we didn't obviously find it so maybe our owner knows more
1628         BOOST_ASSERT(owner());
1629         return owner()->forceDefaultParagraphs(in);
1630 #endif
1631         return false;
1632 }
1633
1634
1635 bool InsetTabular::insertAsciiString(BufferView & bv, string const & buf,
1636                                      bool usePaste)
1637 {
1638         if (buf.length() <= 0)
1639                 return true;
1640
1641         int cols = 1;
1642         int rows = 1;
1643         int maxCols = 1;
1644         string::size_type len = buf.length();
1645         string::size_type p = 0;
1646
1647         while (p < len && (p = buf.find_first_of("\t\n", p)) != string::npos) {
1648                 switch (buf[p]) {
1649                 case '\t':
1650                         ++cols;
1651                         break;
1652                 case '\n':
1653                         if (p + 1 < len)
1654                                 ++rows;
1655                         maxCols = max(cols, maxCols);
1656                         cols = 1;
1657                         break;
1658                 }
1659                 ++p;
1660         }
1661         maxCols = max(cols, maxCols);
1662         LyXTabular * loctab;
1663         int cell = 0;
1664         int ocol = 0;
1665         int row = 0;
1666         if (usePaste) {
1667                 paste_tabular.reset(
1668                         new LyXTabular(bv.buffer()->params(), rows, maxCols));
1669                 loctab = paste_tabular.get();
1670                 cols = 0;
1671         } else {
1672                 loctab = &tabular;
1673                 cell = bv.cursor().idx();
1674                 ocol = tabular.column_of_cell(cell);
1675                 row = tabular.row_of_cell(cell);
1676         }
1677
1678         string::size_type op = 0;
1679         int cells = loctab->getNumberOfCells();
1680         p = 0;
1681         cols = ocol;
1682         rows = loctab->rows();
1683         int const columns = loctab->columns();
1684
1685         while (cell < cells && p < len && row < rows &&
1686                (p = buf.find_first_of("\t\n", p)) != string::npos)
1687         {
1688                 if (p >= len)
1689                         break;
1690                 switch (buf[p]) {
1691                 case '\t':
1692                         // we can only set this if we are not too far right
1693                         if (cols < columns) {
1694                                 InsetText & inset = loctab->getCellInset(cell);
1695                                 Paragraph & par = inset.text_.getPar(0);
1696                                 LyXFont const font = inset.text_.getFont(par, 0);
1697                                 inset.setText(buf.substr(op, p - op), font);
1698                                 ++cols;
1699                                 ++cell;
1700                         }
1701                         break;
1702                 case '\n':
1703                         // we can only set this if we are not too far right
1704                         if (cols < columns) {
1705                                 InsetText & inset = tabular.getCellInset(cell);
1706                                 Paragraph & par = inset.text_.getPar(0);
1707                                 LyXFont const font = inset.text_.getFont(par, 0);
1708                                 inset.setText(buf.substr(op, p - op), font);
1709                         }
1710                         cols = ocol;
1711                         ++row;
1712                         if (row < rows)
1713                                 cell = loctab->getCellNumber(row, cols);
1714                         break;
1715                 }
1716                 ++p;
1717                 op = p;
1718         }
1719         // check for the last cell if there is no trailing '\n'
1720         if (cell < cells && op < len) {
1721                 InsetText & inset = loctab->getCellInset(cell);
1722                 Paragraph & par = inset.text_.getPar(0);
1723                 LyXFont const font = inset.text_.getFont(par, 0);
1724                 inset.setText(buf.substr(op, len - op), font);
1725         }
1726         return true;
1727 }
1728
1729
1730 void InsetTabular::addPreview(PreviewLoader & loader) const
1731 {
1732         int const rows = tabular.rows();
1733         int const columns = tabular.columns();
1734         for (int i = 0; i < rows; ++i) {
1735                 for (int j = 0; j < columns; ++j)
1736                         tabular.getCellInset(i, j).addPreview(loader);
1737         }
1738 }
1739
1740
1741 bool InsetTabular::tablemode(LCursor & cur) const
1742 {
1743         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
1744 }
1745
1746
1747
1748
1749
1750 string const InsetTabularMailer::name_("tabular");
1751
1752 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
1753         : inset_(const_cast<InsetTabular &>(inset))
1754 {}
1755
1756
1757 string const InsetTabularMailer::inset2string(Buffer const &) const
1758 {
1759         return params2string(inset_);
1760 }
1761
1762
1763 int InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
1764 {
1765         istringstream data(in);
1766         LyXLex lex(0,0);
1767         lex.setStream(data);
1768
1769 #ifdef WITH_WARNINGS
1770 #warning CHECK verify that this is a sane value to return.
1771 #endif
1772         if (in.empty())
1773                 return -1;
1774
1775         if (lex.isOK()) {
1776                 lex.next();
1777                 string const token = lex.getString();
1778                 if (token != name_)
1779                         return -1;
1780         }
1781
1782         int cell = -1;
1783         if (lex.isOK()) {
1784                 lex.next();
1785                 string const token = lex.getString();
1786                 if (token != "\\active_cell")
1787                         return -1;
1788                 lex.next();
1789                 cell = lex.getInteger();
1790         }
1791
1792         // This is part of the inset proper that is usually swallowed
1793         // by Buffer::readInset
1794         if (lex.isOK()) {
1795                 lex.next();
1796                 string const token = lex.getString();
1797                 if (token != "Tabular")
1798                         return -1;
1799         }
1800
1801         if (!lex.isOK())
1802                 return -1;
1803
1804         Buffer const & buffer = inset.buffer();
1805         inset.read(buffer, lex);
1806
1807         // We can't set the active cell, but we can tell the frontend
1808         // what it is.
1809         return cell;
1810 }
1811
1812
1813 string const InsetTabularMailer::params2string(InsetTabular const & inset)
1814 {
1815         ostringstream data;
1816 #ifdef WITH_WARNINGS
1817 #warning wrong!
1818 #endif
1819         //data << name_ << " \\active_cell " << inset.getActCell() << '\n';
1820         data << name_ << " \\active_cell " << 0 << '\n';
1821         inset.write(inset.buffer(), data);
1822         data << "\\end_inset\n";
1823         return data.str();
1824 }