]> git.lyx.org Git - lyx.git/blob - src/insets/insettabular.C
use better index types for tabular rows, columns and cells than int
[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         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
267         BufferView * bv = pi.base.bv;
268
269         static NullPainter nop;
270         static PainterInfo nullpi(bv, nop);
271
272         resetPos(bv->cursor());
273
274         setPosCache(pi, x, y);
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                 if (y + d <= 0 && y - a < pi.pain.paperHeight()) {
287                         y += d  + tabular.getAscentOfRow(i + 1)
288                                 + tabular.getAdditionalHeight(i + 1);
289                         continue;
290                 }
291                 for (col_type j = 0; j < tabular.columns(); ++j) {
292                         if (tabular.isPartOfMultiColumn(i, j))
293                                 continue;
294                         if (first_visible_cell == LyXTabular::npos)
295                                 first_visible_cell = idx;
296
297                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
298                         if (nx + tabular.getWidthOfColumn(idx) < 0
299                             || nx > bv->workWidth()
300                             || y - a > bv->workHeight()) {
301                                 cell(idx)->draw(nullpi, cx, y);
302                                 drawCellLines(nop, nx, y, i, idx);
303                         } else {
304                                 cell(idx)->draw(pi, cx, y);
305                                 drawCellLines(pi.pain, nx, y, i, idx);
306                         }
307                         nx += tabular.getWidthOfColumn(idx);
308                         ++idx;
309                 }
310
311                 if (i + 1 < tabular.rows())
312                         y += d + tabular.getAscentOfRow(i + 1) +
313                                 tabular.getAdditionalHeight(i + 1);
314         }
315 }
316
317
318 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
319 {
320         LCursor & cur = pi.base.bv->cursor();
321         if (!cur.selection())
322                 return;
323         if (!ptr_cmp(&cur.inset(), this))
324                 return;
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, y);
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                 }
513                 break;
514
515         case LFUN_LEFTSEL:
516         case LFUN_LEFT:
517                 cell(cur.idx())->dispatch(cur, cmd);
518                 cur.dispatched(); // override the cell's decision
519                 if (sl == cur.top())
520                         isRightToLeft(cur) ? moveNextCell(cur) : movePrevCell(cur);
521                 if (sl == cur.top()) {
522                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
523                         cur.undispatched();
524                 }
525                 break;
526
527         case LFUN_DOWNSEL:
528         case LFUN_DOWN:
529                 cell(cur.idx())->dispatch(cur, cmd);
530                 cur.dispatched(); // override the cell's decision
531                 if (sl == cur.top())
532                         if (tabular.row_of_cell(cur.idx()) != tabular.rows() - 1) {
533                                 cur.idx() = tabular.getCellBelow(cur.idx());
534                                 cur.pit() = 0;
535                                 cur.pos() = 0;
536                                 resetPos(cur);
537                         }
538                 if (sl == cur.top()) {
539                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
540                         cur.undispatched();
541                         resetPos(cur);
542                 }
543                 break;
544
545         case LFUN_UPSEL:
546         case LFUN_UP:
547                 cell(cur.idx())->dispatch(cur, cmd);
548                 cur.dispatched(); // override the cell's decision
549                 if (sl == cur.top())
550                         if (tabular.row_of_cell(cur.idx()) != 0) {
551                                 cur.idx() = tabular.getCellAbove(cur.idx());
552                                 cur.pit() = cur.lastpit();
553                                 cur.pos() = cur.lastpos();
554                                 resetPos(cur);
555                         }
556                 if (sl == cur.top()) {
557                         cmd = FuncRequest(LFUN_FINISHED_UP);
558                         cur.undispatched();
559                         resetPos(cur);
560                 }
561                 break;
562
563 //      case LFUN_NEXT: {
564 //              //if (hasSelection())
565 //              //      cur.selection() = false;
566 //              col_type const col = tabular.column_of_cell(cur.idx());
567 //              int const t =   cur.bv().top_y() + cur.bv().painter().paperHeight();
568 //              if (t < yo() + tabular.getHeightOfTabular()) {
569 //                      cur.bv().scrollDocView(t);
570 //                      cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
571 //              } else {
572 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
573 //              }
574 //              cur.par() = 0;
575 //              cur.pos() = 0;
576 //              resetPos(cur);
577 //              break;
578 //      }
579 //
580 //      case LFUN_PRIOR: {
581 //              //if (hasSelection())
582 //              //      cur.selection() = false;
583 //              col_type const col = tabular.column_of_cell(cur.idx());
584 //              int const t =   cur.bv().top_y() + cur.bv().painter().paperHeight();
585 //              if (yo() < 0) {
586 //                      cur.bv().scrollDocView(t);
587 //                      if (yo() > 0)
588 //                              cur.idx() = col;
589 //                      else
590 //                              cur.idx() = tabular.getCellBelow(first_visible_cell) + col;
591 //              } else {
592 //                      cur.idx() = col;
593 //              }
594 //              cur.par() = cur.lastpar();
595 //              cur.pos() = cur.lastpos();
596 //              resetPos(cur);
597 //              break;
598 //      }
599
600         case LFUN_LAYOUT_TABULAR:
601                 InsetTabularMailer(*this).showDialog(&cur.bv());
602                 break;
603
604         case LFUN_INSET_DIALOG_UPDATE:
605                 InsetTabularMailer(*this).updateDialog(&cur.bv());
606                 break;
607
608         case LFUN_TABULAR_FEATURE:
609                 if (!tabularFeatures(cur, cmd.argument))
610                         cur.undispatched();
611                 break;
612
613         // insert file functions
614         case LFUN_FILE_INSERT_ASCII_PARA:
615         case LFUN_FILE_INSERT_ASCII: {
616                 string const tmpstr = getContentsOfAsciiFile(&cur.bv(), cmd.argument, false);
617                 if (!tmpstr.empty() && !insertAsciiString(cur.bv(), tmpstr, false))
618                         cur.undispatched();
619                 break;
620         }
621
622         case LFUN_CUT:
623                 if (copySelection(cur)) {
624                         recordUndo(cur, Undo::DELETE);
625                         cutSelection(cur);
626                 }
627                 break;
628
629         case LFUN_BACKSPACE:
630         case LFUN_DELETE:
631                 recordUndo(cur, Undo::DELETE);
632                 if (tablemode(cur))
633                         cutSelection(cur);
634                 else
635                         cell(cur.idx())->dispatch(cur, cmd);
636                 break;
637
638         case LFUN_COPY:
639                 if (!cur.selection())
640                         break;
641                 finishUndo();
642                 copySelection(cur);
643                 break;
644
645         case LFUN_PASTESELECTION: {
646                 string const clip = cur.bv().getClipboard();
647                 if (clip.empty())
648                         break;
649                 if (clip.find('\t') != string::npos) {
650                         col_type cols = 1;
651                         row_type rows = 1;
652                         col_type maxCols = 1;
653                         size_t len = clip.length();
654                         for (size_t p = 0; p < len; ++p) {
655                                 p = clip.find_first_of("\t\n", p);
656                                 if (p == string::npos)
657                                         break;
658                                 switch (clip[p]) {
659                                 case '\t':
660                                         ++cols;
661                                         break;
662                                 case '\n':
663                                         if (p + 1 < len)
664                                                 ++rows;
665                                         maxCols = max(cols, maxCols);
666                                         cols = 1;
667                                         break;
668                                 }
669                         }
670                         maxCols = max(cols, maxCols);
671
672                         paste_tabular.reset(
673                                 new LyXTabular(cur.buffer().params(), rows, maxCols));
674
675                         string::size_type op = 0;
676                         idx_type cell = 0;
677                         idx_type const cells =
678                                 paste_tabular->getNumberOfCells();
679                         cols = 0;
680                         LyXFont font;
681                         for (size_t p = 0; cell < cells && p < len; ++p) {
682                                 p = clip.find_first_of("\t\n", p);
683                                 if (p == string::npos || p >= len)
684                                         break;
685                                 switch (clip[p]) {
686                                 case '\t':
687                                         paste_tabular->getCellInset(cell)->
688                                                 setText(clip.substr(op, p - op), font);
689                                         ++cols;
690                                         ++cell;
691                                         break;
692                                 case '\n':
693                                         paste_tabular->getCellInset(cell)->
694                                                 setText(clip.substr(op, p - op), font);
695                                         while (cols++ < maxCols)
696                                                 ++cell;
697                                         cols = 0;
698                                         break;
699                                 }
700                                 op = p + 1;
701                         }
702                         // check for the last cell if there is no trailing '\n'
703                         if (cell < cells && op < len)
704                                 paste_tabular->getCellInset(cell)->
705                                         setText(clip.substr(op, len - op), font);
706                 } else if (!insertAsciiString(cur.bv(), clip, true)) {
707                         // so that the clipboard is used and it goes on
708                         // to default
709                         // and executes LFUN_PASTESELECTION in insettext!
710                         paste_tabular.reset();
711                 }
712                 // fall through
713         }
714
715         case LFUN_PASTE:
716                 if (hasPasteBuffer()) {
717                         recordUndo(cur, Undo::INSERT);
718                         pasteSelection(cur);
719                         break;
720                 }
721                 cell(cur.idx())->dispatch(cur, cmd);
722                 break;
723
724         default:
725                 // we try to handle this event in the insets dispatch function.
726                 cell(cur.idx())->dispatch(cur, cmd);
727                 break;
728         }
729
730         InsetTabularMailer(*this).updateDialog(&cur.bv());
731 }
732
733
734 // function sets an object as defined in func_status.h:
735 // states OK, Unknown, Disabled, On, Off.
736 bool InsetTabular::getStatus(LCursor & cur, FuncRequest const & cmd,
737         FuncStatus & status) const
738 {
739         switch (cmd.action) {
740         case LFUN_TABULAR_FEATURE: {
741                 int action = LyXTabular::LAST_ACTION;
742                 int i = 0;
743                 for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
744                         string const tmp = tabularFeature[i].feature;
745                         if (tmp == cmd.argument.substr(0, tmp.length())) {
746                                 action = tabularFeature[i].action;
747                                 break;
748                         }
749                 }
750                 if (action == LyXTabular::LAST_ACTION) {
751                         status.clear();
752                         status.unknown(true);
753                         return true;
754                 }
755
756                 string const argument
757                         = ltrim(cmd.argument.substr(tabularFeature[i].feature.length()));
758
759                 row_type sel_row_start = 0;
760                 row_type sel_row_end = 0;
761                 col_type dummy;
762                 LyXTabular::ltType dummyltt;
763                 bool flag = true;
764
765                 getSelection(cur, sel_row_start, sel_row_end, dummy, dummy);
766
767                 switch (action) {
768                 case LyXTabular::SET_PWIDTH:
769                 case LyXTabular::SET_MPWIDTH:
770                 case LyXTabular::SET_SPECIAL_COLUMN:
771                 case LyXTabular::SET_SPECIAL_MULTI:
772                 case LyXTabular::APPEND_ROW:
773                 case LyXTabular::APPEND_COLUMN:
774                 case LyXTabular::DELETE_ROW:
775                 case LyXTabular::DELETE_COLUMN:
776                 case LyXTabular::SET_ALL_LINES:
777                 case LyXTabular::UNSET_ALL_LINES:
778                         status.clear();
779                         return true;
780
781                 case LyXTabular::MULTICOLUMN:
782                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
783                         break;
784
785                 case LyXTabular::M_TOGGLE_LINE_TOP:
786                         flag = false;
787                 case LyXTabular::TOGGLE_LINE_TOP:
788                         status.setOnOff(tabular.topLine(cur.idx(), flag));
789                         break;
790
791                 case LyXTabular::M_TOGGLE_LINE_BOTTOM:
792                         flag = false;
793                 case LyXTabular::TOGGLE_LINE_BOTTOM:
794                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
795                         break;
796
797                 case LyXTabular::M_TOGGLE_LINE_LEFT:
798                         flag = false;
799                 case LyXTabular::TOGGLE_LINE_LEFT:
800                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
801                         break;
802
803                 case LyXTabular::M_TOGGLE_LINE_RIGHT:
804                         flag = false;
805                 case LyXTabular::TOGGLE_LINE_RIGHT:
806                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
807                         break;
808
809                 case LyXTabular::M_ALIGN_LEFT:
810                         flag = false;
811                 case LyXTabular::ALIGN_LEFT:
812                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
813                         break;
814
815                 case LyXTabular::M_ALIGN_RIGHT:
816                         flag = false;
817                 case LyXTabular::ALIGN_RIGHT:
818                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
819                         break;
820
821                 case LyXTabular::M_ALIGN_CENTER:
822                         flag = false;
823                 case LyXTabular::ALIGN_CENTER:
824                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
825                         break;
826
827                 case LyXTabular::ALIGN_BLOCK:
828                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
829                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
830                         break;
831
832                 case LyXTabular::M_VALIGN_TOP:
833                         flag = false;
834                 case LyXTabular::VALIGN_TOP:
835                         status.setOnOff(
836                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_TOP);
837                         break;
838
839                 case LyXTabular::M_VALIGN_BOTTOM:
840                         flag = false;
841                 case LyXTabular::VALIGN_BOTTOM:
842                         status.setOnOff(
843                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_BOTTOM);
844                         break;
845
846                 case LyXTabular::M_VALIGN_MIDDLE:
847                         flag = false;
848                 case LyXTabular::VALIGN_MIDDLE:
849                         status.setOnOff(
850                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_MIDDLE);
851                         break;
852
853                 case LyXTabular::SET_LONGTABULAR:
854                         status.setOnOff(tabular.isLongTabular());
855                         break;
856
857                 case LyXTabular::UNSET_LONGTABULAR:
858                         status.setOnOff(!tabular.isLongTabular());
859                         break;
860
861                 case LyXTabular::SET_ROTATE_TABULAR:
862                         status.setOnOff(tabular.getRotateTabular());
863                         break;
864
865                 case LyXTabular::UNSET_ROTATE_TABULAR:
866                         status.setOnOff(!tabular.getRotateTabular());
867                         break;
868
869                 case LyXTabular::SET_ROTATE_CELL:
870                         status.setOnOff(tabular.getRotateCell(cur.idx()));
871                         break;
872
873                 case LyXTabular::UNSET_ROTATE_CELL:
874                         status.setOnOff(!tabular.getRotateCell(cur.idx()));
875                         break;
876
877                 case LyXTabular::SET_USEBOX:
878                         status.setOnOff(strToInt(argument) == tabular.getUsebox(cur.idx()));
879                         break;
880
881                 case LyXTabular::SET_LTFIRSTHEAD:
882                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
883                         break;
884
885                 case LyXTabular::SET_LTHEAD:
886                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
887                         break;
888
889                 case LyXTabular::SET_LTFOOT:
890                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
891                         break;
892
893                 case LyXTabular::SET_LTLASTFOOT:
894                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
895                         break;
896
897                 case LyXTabular::SET_LTNEWPAGE:
898                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
899                         break;
900
901                 default:
902                         status.clear();
903                         status.enabled(false);
904                         break;
905                 }
906                 return true;
907         }
908
909         default:
910                 // we try to handle this event in the insets dispatch function.
911                 return cell(cur.idx())->getStatus(cur, cmd, status);
912         }
913 }
914
915
916 int InsetTabular::latex(Buffer const & buf, ostream & os,
917                         OutputParams const & runparams) const
918 {
919         return tabular.latex(buf, os, runparams);
920 }
921
922
923 int InsetTabular::plaintext(Buffer const & buf, ostream & os,
924                         OutputParams const & runparams) const
925 {
926         int const dp = runparams.linelen ? runparams.depth : 0;
927         return tabular.plaintext(buf, os, runparams, dp, false, 0);
928 }
929
930
931 int InsetTabular::linuxdoc(Buffer const & buf, ostream & os,
932                            OutputParams const & runparams) const
933 {
934         return tabular.linuxdoc(buf,os, runparams);
935 }
936
937
938 int InsetTabular::docbook(Buffer const & buf, ostream & os,
939                           OutputParams const & runparams) const
940 {
941         int ret = 0;
942         InsetBase * master = 0;
943
944 #ifdef WITH_WARNINGS
945 #warning Why not pass a proper DocIterator here?
946 #endif
947 #if 0
948         // if the table is inside a float it doesn't need the informaltable
949         // wrapper. Search for it.
950         for (master = owner(); master; master = master->owner())
951                 if (master->lyxCode() == InsetBase::FLOAT_CODE)
952                         break;
953 #endif
954
955         if (!master) {
956                 os << "<informaltable>";
957                 ++ret;
958         }
959         ret += tabular.docbook(buf, os, runparams);
960         if (!master) {
961                 os << "</informaltable>";
962                 ++ret;
963         }
964         return ret;
965 }
966
967
968 void InsetTabular::validate(LaTeXFeatures & features) const
969 {
970         tabular.validate(features);
971 }
972
973
974 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
975 {
976         return tabular.getCellInset(idx);
977 }
978
979
980 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
981 {
982         return tabular.getCellInset(idx);
983 }
984
985
986 void InsetTabular::getCursorPos(CursorSlice const & sl, int & x, int & y) const
987 {
988         cell(sl.idx())->getCursorPos(sl, x, y);
989
990         // y offset     correction
991         int const row = tabular.row_of_cell(sl.idx());
992         for (int i = 0; i <= row; ++i) {
993                 if (i != 0) {
994                         y += tabular.getAscentOfRow(i);
995                         y += tabular.getAdditionalHeight(i);
996                 }
997                 if (i != row)
998                         y += tabular.getDescentOfRow(i);
999         }
1000
1001         // x offset     correction
1002         int const col = tabular.column_of_cell(sl.idx());
1003         int idx = tabular.getCellNumber(row, 0);
1004         for (int j = 0; j < col; ++j) {
1005                 if (tabular.isPartOfMultiColumn(row, j))
1006                         continue;
1007                 x += tabular.getWidthOfColumn(idx);
1008                 ++idx;
1009         }
1010         x += tabular.getBeginningOfTextInCell(idx);
1011         x += ADD_TO_TABULAR_WIDTH;
1012         x += scroll();
1013 }
1014
1015
1016 namespace  {
1017         
1018
1019 // Manhattan distance to nearest corner
1020 int dist(InsetOld const & inset, int x, int y)
1021 {
1022         int xx = 0;
1023         int yy = 0;
1024         Point o = theCoords.insets_.xy(&inset);
1025         int const xo = o.x_;
1026         int const yo = o.y_;
1027
1028         if (x < xo)
1029                 xx = xo - x;
1030         else if (x > xo + inset.width())
1031                 xx = x - xo - inset.width();
1032
1033         if (y < yo - inset.ascent())
1034                 yy = yo - inset.ascent() - y;
1035         else if (y > yo + inset.descent())
1036                 yy = y - yo - inset.descent();
1037
1038         lyxerr << " xo_=" << xo << "  yo_=" << yo
1039                << " width_=" << inset.width() << " ascent=" << inset.ascent()
1040                << " descent=" << inset.descent()
1041                << " dist=" << xx + yy << endl;
1042         return xx + yy;
1043 }
1044
1045
1046 } //namespace anon
1047
1048
1049 InsetBase * InsetTabular::setPos(LCursor & cur, int x, int y) const
1050 {
1051         lyxerr << "# InsetTabular::setPos()  x=" << x << " y=" << y << endl;
1052         idx_type idx_min = 0;
1053         int dist_min = std::numeric_limits<int>::max();
1054         for (idx_type i = 0; i < nargs(); ++i) {
1055                 if (theCoords.insets_.has(tabular.getCellInset(i).get())) {
1056                         int d = dist(*tabular.getCellInset(i), x, y);
1057                         if (d < dist_min) {
1058                                 dist_min = d;
1059                                 idx_min = i;
1060                         }
1061                 }
1062         }
1063         cur.idx() = idx_min;
1064         //lyxerr << "# InsetTabular::setPos()\n" << cur << endl;
1065         return cell(cur.idx())->text_.editXY(cur, x, y);
1066 }
1067
1068
1069 int InsetTabular::getCellXPos(idx_type const cell) const
1070 {
1071         idx_type c = cell;
1072
1073         for (; !tabular.isFirstCellInRow(c); --c)
1074                 ;
1075         int lx = tabular.getWidthOfColumn(cell);
1076         for (; c < cell; ++c)
1077                 lx += tabular.getWidthOfColumn(c);
1078
1079         return lx - tabular.getWidthOfColumn(cell) + xo();
1080 }
1081
1082
1083 void InsetTabular::resetPos(LCursor & cur) const
1084 {
1085         
1086         
1087         BufferView & bv = cur.bv();
1088 //      col_type const actcol = tabular.column_of_cell(cur.idx());
1089 //      int const offset = ADD_TO_TABULAR_WIDTH + 2;
1090 //      int const new_x = getCellXPos(cur.idx()) + offset;
1091 //      int const old_x = cursorx_;
1092 //      int const col_width = tabular.getWidthOfColumn(cur.idx());
1093 //      cursorx_ = new_x;
1094 //    cursor.x(getCellXPos(cur.idx()) + offset);
1095 //      if (actcol < tabular.columns() - 1 && scroll(false) &&
1096 //              tabular.getWidthOfTabular() < bv.workWidth()-20)
1097 //      {
1098 //              scroll(bv, 0.0F);
1099 //      } else if (cursorx_ - offset > 20 &&
1100 //                 cursorx_ - offset + col_width > bv.workWidth() - 20) {
1101 //              scroll(bv, - col_width - 20);
1102 //      } else if (cursorx_ - offset < 20) {
1103 //              scroll(bv, 20 - cursorx_ + offset);
1104 //      } else if (scroll() && xo() > 20 &&
1105 //                 xo() + tabular.getWidthOfTabular() > bv.workWidth() - 20) {
1106 //              scroll(bv, old_x - cursorx_);
1107 //      }
1108
1109         if (&cur.inset() != this) {
1110                 scroll(bv, 0);
1111         } else {
1112                 int const X1 = 0;
1113                 int const X2 = bv.workWidth();
1114                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
1115                 int const col_width = tabular.getWidthOfColumn(cur.idx());
1116                 int const x1 = getCellXPos(cur.idx()) + offset + scroll();
1117                 int const x2 = x1 + col_width;
1118
1119                 if (x1 < X1 + 20)
1120                         scroll(bv, X1 + 20 - x1);
1121                 else if (x2 > X2 - 20)
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 #if 0
1462                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1463                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1464                                 tabular.setAllLines(
1465                                         tabular.getCellNumber(i,j), setLines);
1466 #endif
1467                 break;
1468
1469         case LyXTabular::SET_LONGTABULAR:
1470                 tabular.setLongTabular(true);
1471                 break;
1472
1473         case LyXTabular::UNSET_LONGTABULAR:
1474                 tabular.setLongTabular(false);
1475                 break;
1476
1477         case LyXTabular::SET_ROTATE_TABULAR:
1478                 tabular.setRotateTabular(true);
1479                 break;
1480
1481         case LyXTabular::UNSET_ROTATE_TABULAR:
1482                 tabular.setRotateTabular(false);
1483                 break;
1484
1485         case LyXTabular::SET_ROTATE_CELL:
1486                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1487                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1488                                 tabular.setRotateCell(
1489                                         tabular.getCellNumber(i, j), true);
1490                 break;
1491
1492         case LyXTabular::UNSET_ROTATE_CELL:
1493                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1494                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1495                                 tabular.setRotateCell(
1496                                         tabular.getCellNumber(i, j), false);
1497                 break;
1498
1499         case LyXTabular::SET_USEBOX: {
1500                 LyXTabular::BoxType val = LyXTabular::BoxType(strToInt(value));
1501                 if (val == tabular.getUsebox(cur.idx()))
1502                         val = LyXTabular::BOX_NONE;
1503                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1504                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1505                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1506                 break;
1507         }
1508
1509         case LyXTabular::UNSET_LTFIRSTHEAD:
1510                 flag = false;
1511         case LyXTabular::SET_LTFIRSTHEAD:
1512                 tabular.getRowOfLTFirstHead(row, ltt);
1513                 checkLongtableSpecial(ltt, value, flag);
1514                 tabular.setLTHead(row, flag, ltt, true);
1515                 break;
1516
1517         case LyXTabular::UNSET_LTHEAD:
1518                 flag = false;
1519         case LyXTabular::SET_LTHEAD:
1520                 tabular.getRowOfLTHead(row, ltt);
1521                 checkLongtableSpecial(ltt, value, flag);
1522                 tabular.setLTHead(row, flag, ltt, false);
1523                 break;
1524
1525         case LyXTabular::UNSET_LTFOOT:
1526                 flag = false;
1527         case LyXTabular::SET_LTFOOT:
1528                 tabular.getRowOfLTFoot(row, ltt);
1529                 checkLongtableSpecial(ltt, value, flag);
1530                 tabular.setLTFoot(row, flag, ltt, false);
1531                 break;
1532
1533         case LyXTabular::UNSET_LTLASTFOOT:
1534                 flag = false;
1535         case LyXTabular::SET_LTLASTFOOT:
1536                 tabular.getRowOfLTLastFoot(row, ltt);
1537                 checkLongtableSpecial(ltt, value, flag);
1538                 tabular.setLTFoot(row, flag, ltt, true);
1539                 break;
1540
1541         case LyXTabular::SET_LTNEWPAGE:
1542                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1543                 break;
1544
1545         // dummy stuff just to avoid warnings
1546         case LyXTabular::LAST_ACTION:
1547                 break;
1548         }
1549
1550         InsetTabularMailer(*this).updateDialog(&bv);
1551 }
1552
1553
1554 bool InsetTabular::showInsetDialog(BufferView * bv) const
1555 {
1556         InsetTabularMailer(*this).showDialog(bv);
1557         return true;
1558 }
1559
1560
1561 void InsetTabular::openLayoutDialog(BufferView * bv) const
1562 {
1563         InsetTabularMailer(*this).showDialog(bv);
1564 }
1565
1566
1567 void InsetTabular::getLabelList(Buffer const & buffer,
1568                                 vector<string> & list) const
1569 {
1570         tabular.getLabelList(buffer, list);
1571 }
1572
1573
1574 bool InsetTabular::copySelection(LCursor & cur)
1575 {
1576         if (!cur.selection())
1577                 return false;
1578
1579         row_type rs, re;
1580         col_type cs, ce;
1581         getSelection(cur, rs, re, cs, ce);
1582
1583         paste_tabular.reset(new LyXTabular(tabular));
1584
1585         for (row_type i = 0; i < rs; ++i)
1586                 paste_tabular->deleteRow(0);
1587
1588         row_type const rows = re - rs + 1;
1589         while (paste_tabular->rows() > rows)
1590                 paste_tabular->deleteRow(rows);
1591
1592         paste_tabular->setTopLine(0, true, true);
1593         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
1594                                      true, true);
1595
1596         for (col_type i = 0; i < cs; ++i)
1597                 paste_tabular->deleteColumn(0);
1598
1599         col_type const columns = ce - cs + 1;
1600         while (paste_tabular->columns() > columns)
1601                 paste_tabular->deleteColumn(columns);
1602
1603         paste_tabular->setLeftLine(0, true, true);
1604         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
1605                                     true, true);
1606
1607         ostringstream os;
1608         OutputParams const runparams;
1609         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
1610         cur.bv().stuffClipboard(os.str());
1611         return true;
1612 }
1613
1614
1615 bool InsetTabular::pasteSelection(LCursor & cur)
1616 {
1617         if (!paste_tabular)
1618                 return false;
1619         col_type const actcol = tabular.column_of_cell(cur.idx());
1620         row_type const actrow = tabular.row_of_cell(cur.idx());
1621         for (row_type r1 = 0, r2 = actrow;
1622              r1 < paste_tabular->rows() && r2 < tabular.rows();
1623              ++r1, ++r2) {
1624                 for (col_type c1 = 0, c2 = actcol;
1625                     c1 < paste_tabular->columns() && c2 < tabular.columns();
1626                     ++c1, ++c2) {
1627                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
1628                             tabular.isPartOfMultiColumn(r2, c2))
1629                                 continue;
1630                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
1631                                 --c2;
1632                                 continue;
1633                         }
1634                         if (tabular.isPartOfMultiColumn(r2, c2)) {
1635                                 --c1;
1636                                 continue;
1637                         }
1638                         shared_ptr<InsetText> inset = tabular.getCellInset(r2, c2);
1639                         inset = paste_tabular->getCellInset(r1, c1);
1640                         inset->markNew();
1641                 }
1642         }
1643         return true;
1644 }
1645
1646
1647 void InsetTabular::cutSelection(LCursor & cur)
1648 {
1649         if (!cur.selection())
1650                 return;
1651
1652         bool const track = cur.buffer().params().tracking_changes;
1653         row_type rs, re;
1654         col_type cs, ce;
1655         getSelection(cur, rs, re, cs, ce);
1656         for (row_type i = rs; i <= re; ++i)
1657                 for (col_type j = cs; j <= ce; ++j)
1658                         cell(tabular.getCellNumber(i, j))->clear(track);
1659
1660         // cursor position might be invalid now
1661         cur.pos() = cur.lastpos();
1662         cur.clearSelection();
1663 }
1664
1665
1666 bool InsetTabular::isRightToLeft(LCursor & cur) const
1667 {
1668         BOOST_ASSERT(cur.size() > 1);
1669         Paragraph const & parentpar = cur[cur.size() - 2].paragraph();
1670         LCursor::pos_type const parentpos = cur[cur.size() - 2].pos();
1671         return parentpar.getFontSettings(cur.bv().buffer()->params(),
1672                                          parentpos).language()->RightToLeft();
1673 }
1674
1675
1676 void InsetTabular::getSelection(LCursor & cur,
1677         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
1678 {
1679         CursorSlice const & beg = cur.selBegin();
1680         CursorSlice const & end = cur.selEnd();
1681         cs = tabular.column_of_cell(beg.idx());
1682         ce = tabular.column_of_cell(end.idx());
1683         if (cs > ce) {
1684                 ce = cs;
1685                 cs = tabular.column_of_cell(end.idx());
1686         } else {
1687                 ce = tabular.right_column_of_cell(end.idx());
1688         }
1689
1690         rs = tabular.row_of_cell(beg.idx());
1691         re = tabular.row_of_cell(end.idx());
1692         if (rs > re)
1693                 swap(rs, re);
1694 }
1695
1696
1697 size_t InsetTabular::nargs() const
1698 {
1699         return tabular.getNumberOfCells();
1700 }
1701
1702
1703 LyXText * InsetTabular::getText(int idx) const
1704 {
1705         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
1706 }
1707
1708
1709 void InsetTabular::markErased()
1710 {
1711         for (idx_type idx = 0; idx < nargs(); ++idx)
1712                 cell(idx)->markErased();
1713 }
1714
1715
1716 bool InsetTabular::forceDefaultParagraphs(InsetBase const *) const
1717 {
1718 #if 0
1719         idx_type const cell = tabular.getCellFromInset(in);
1720         // FIXME: getCellFromInset() returns now always a valid cell, so
1721         // the stuff below can be deleted, and instead we have:
1722         return tabular.getPWidth(cell).zero();
1723
1724         if (cell != npos)
1725                 return tabular.getPWidth(cell).zero();
1726
1727         // this is a workaround for a crash (New, Insert->Tabular,
1728         // Insert->FootNote)
1729         if (!owner())
1730                 return false;
1731
1732         // well we didn't obviously find it so maybe our owner knows more
1733         BOOST_ASSERT(owner());
1734         return owner()->forceDefaultParagraphs(in);
1735 #endif
1736         return false;
1737 }
1738
1739
1740 bool InsetTabular::insertAsciiString(BufferView & bv, string const & buf,
1741                                      bool usePaste)
1742 {
1743         if (buf.length() <= 0)
1744                 return true;
1745
1746         col_type cols = 1;
1747         row_type rows = 1;
1748         col_type maxCols = 1;
1749         string::size_type const len = buf.length();
1750         string::size_type p = 0;
1751
1752         while (p < len && (p = buf.find_first_of("\t\n", p)) != string::npos) {
1753                 switch (buf[p]) {
1754                 case '\t':
1755                         ++cols;
1756                         break;
1757                 case '\n':
1758                         if (p + 1 < len)
1759                                 ++rows;
1760                         maxCols = max(cols, maxCols);
1761                         cols = 1;
1762                         break;
1763                 }
1764                 ++p;
1765         }
1766         maxCols = max(cols, maxCols);
1767         LyXTabular * loctab;
1768         idx_type cell = 0;
1769         col_type ocol = 0;
1770         row_type row = 0;
1771         if (usePaste) {
1772                 paste_tabular.reset(
1773                         new LyXTabular(bv.buffer()->params(), rows, maxCols));
1774                 loctab = paste_tabular.get();
1775                 cols = 0;
1776         } else {
1777                 loctab = &tabular;
1778                 cell = bv.cursor().idx();
1779                 ocol = tabular.column_of_cell(cell);
1780                 row = tabular.row_of_cell(cell);
1781         }
1782
1783         string::size_type op = 0;
1784         idx_type const cells = loctab->getNumberOfCells();
1785         p = 0;
1786         cols = ocol;
1787         rows = loctab->rows();
1788         col_type const columns = loctab->columns();
1789
1790         while (cell < cells && p < len && row < rows &&
1791                (p = buf.find_first_of("\t\n", p)) != string::npos)
1792         {
1793                 if (p >= len)
1794                         break;
1795                 switch (buf[p]) {
1796                 case '\t':
1797                         // we can only set this if we are not too far right
1798                         if (cols < columns) {
1799                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
1800                                 Paragraph & par = inset->text_.getPar(0);
1801                                 LyXFont const font = inset->text_.getFont(par, 0);
1802                                 inset->setText(buf.substr(op, p - op), font);
1803                                 ++cols;
1804                                 ++cell;
1805                         }
1806                         break;
1807                 case '\n':
1808                         // we can only set this if we are not too far right
1809                         if (cols < columns) {
1810                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
1811                                 Paragraph & par = inset->text_.getPar(0);
1812                                 LyXFont const font = inset->text_.getFont(par, 0);
1813                                 inset->setText(buf.substr(op, p - op), font);
1814                         }
1815                         cols = ocol;
1816                         ++row;
1817                         if (row < rows)
1818                                 cell = loctab->getCellNumber(row, cols);
1819                         break;
1820                 }
1821                 ++p;
1822                 op = p;
1823         }
1824         // check for the last cell if there is no trailing '\n'
1825         if (cell < cells && op < len) {
1826                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
1827                 Paragraph & par = inset->text_.getPar(0);
1828                 LyXFont const font = inset->text_.getFont(par, 0);
1829                 inset->setText(buf.substr(op, len - op), font);
1830         }
1831         return true;
1832 }
1833
1834
1835 void InsetTabular::addPreview(PreviewLoader & loader) const
1836 {
1837         row_type const rows = tabular.rows();
1838         col_type const columns = tabular.columns();
1839         for (row_type i = 0; i < rows; ++i) {
1840                 for (col_type j = 0; j < columns; ++j)
1841                         tabular.getCellInset(i, j)->addPreview(loader);
1842         }
1843 }
1844
1845
1846 bool InsetTabular::tablemode(LCursor & cur) const
1847 {
1848         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
1849 }
1850
1851
1852
1853
1854
1855 string const InsetTabularMailer::name_("tabular");
1856
1857 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
1858         : inset_(const_cast<InsetTabular &>(inset))
1859 {}
1860
1861
1862 string const InsetTabularMailer::inset2string(Buffer const &) const
1863 {
1864         return params2string(inset_);
1865 }
1866
1867
1868 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
1869 {
1870         istringstream data(in);
1871         LyXLex lex(0,0);
1872         lex.setStream(data);
1873
1874         if (in.empty())
1875                 return;
1876
1877         string token;
1878         lex >> token;
1879         if (!lex || token != name_)
1880                 return print_mailer_error("InsetTabularMailer", in, 1,
1881                                           name_);
1882
1883         // This is part of the inset proper that is usually swallowed
1884         // by Buffer::readInset
1885         lex >> token;
1886         if (!lex || token != "Tabular")
1887                 return print_mailer_error("InsetTabularMailer", in, 2,
1888                                           "Tabular");
1889
1890         Buffer const & buffer = inset.buffer();
1891         inset.read(buffer, lex);
1892 }
1893
1894
1895 string const InsetTabularMailer::params2string(InsetTabular const & inset)
1896 {
1897         ostringstream data;
1898         data << name_ << ' ';
1899         inset.write(inset.buffer(), data);
1900         data << "\\end_inset\n";
1901         return data.str();
1902 }