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