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