]> git.lyx.org Git - lyx.git/blob - src/insets/insettabular.C
the convert patch
[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         default:
728                 // we try to handle this event in the insets dispatch function.
729                 cell(cur.idx())->dispatch(cur, cmd);
730                 break;
731         }
732
733         InsetTabularMailer(*this).updateDialog(&cur.bv());
734 }
735
736
737 // function sets an object as defined in func_status.h:
738 // states OK, Unknown, Disabled, On, Off.
739 bool InsetTabular::getStatus(LCursor & cur, FuncRequest const & cmd,
740         FuncStatus & status) const
741 {
742         switch (cmd.action) {
743         case LFUN_TABULAR_FEATURE: {
744                 int action = LyXTabular::LAST_ACTION;
745                 int i = 0;
746                 for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
747                         string const tmp = tabularFeature[i].feature;
748                         if (tmp == cmd.argument.substr(0, tmp.length())) {
749                                 action = tabularFeature[i].action;
750                                 break;
751                         }
752                 }
753                 if (action == LyXTabular::LAST_ACTION) {
754                         status.clear();
755                         status.unknown(true);
756                         return true;
757                 }
758
759                 string const argument
760                         = ltrim(cmd.argument.substr(tabularFeature[i].feature.length()));
761
762                 row_type sel_row_start = 0;
763                 row_type sel_row_end = 0;
764                 col_type dummy;
765                 LyXTabular::ltType dummyltt;
766                 bool flag = true;
767
768                 getSelection(cur, sel_row_start, sel_row_end, dummy, dummy);
769
770                 switch (action) {
771                 case LyXTabular::SET_PWIDTH:
772                 case LyXTabular::SET_MPWIDTH:
773                 case LyXTabular::SET_SPECIAL_COLUMN:
774                 case LyXTabular::SET_SPECIAL_MULTI:
775                 case LyXTabular::APPEND_ROW:
776                 case LyXTabular::APPEND_COLUMN:
777                 case LyXTabular::DELETE_ROW:
778                 case LyXTabular::DELETE_COLUMN:
779                 case LyXTabular::SET_ALL_LINES:
780                 case LyXTabular::UNSET_ALL_LINES:
781                         status.clear();
782                         return true;
783
784                 case LyXTabular::MULTICOLUMN:
785                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
786                         break;
787
788                 case LyXTabular::M_TOGGLE_LINE_TOP:
789                         flag = false;
790                 case LyXTabular::TOGGLE_LINE_TOP:
791                         status.setOnOff(tabular.topLine(cur.idx(), flag));
792                         break;
793
794                 case LyXTabular::M_TOGGLE_LINE_BOTTOM:
795                         flag = false;
796                 case LyXTabular::TOGGLE_LINE_BOTTOM:
797                         status.setOnOff(tabular.bottomLine(cur.idx(), flag));
798                         break;
799
800                 case LyXTabular::M_TOGGLE_LINE_LEFT:
801                         flag = false;
802                 case LyXTabular::TOGGLE_LINE_LEFT:
803                         status.setOnOff(tabular.leftLine(cur.idx(), flag));
804                         break;
805
806                 case LyXTabular::M_TOGGLE_LINE_RIGHT:
807                         flag = false;
808                 case LyXTabular::TOGGLE_LINE_RIGHT:
809                         status.setOnOff(tabular.rightLine(cur.idx(), flag));
810                         break;
811
812                 case LyXTabular::M_ALIGN_LEFT:
813                         flag = false;
814                 case LyXTabular::ALIGN_LEFT:
815                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
816                         break;
817
818                 case LyXTabular::M_ALIGN_RIGHT:
819                         flag = false;
820                 case LyXTabular::ALIGN_RIGHT:
821                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
822                         break;
823
824                 case LyXTabular::M_ALIGN_CENTER:
825                         flag = false;
826                 case LyXTabular::ALIGN_CENTER:
827                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
828                         break;
829
830                 case LyXTabular::ALIGN_BLOCK:
831                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
832                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
833                         break;
834
835                 case LyXTabular::M_VALIGN_TOP:
836                         flag = false;
837                 case LyXTabular::VALIGN_TOP:
838                         status.setOnOff(
839                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_TOP);
840                         break;
841
842                 case LyXTabular::M_VALIGN_BOTTOM:
843                         flag = false;
844                 case LyXTabular::VALIGN_BOTTOM:
845                         status.setOnOff(
846                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_BOTTOM);
847                         break;
848
849                 case LyXTabular::M_VALIGN_MIDDLE:
850                         flag = false;
851                 case LyXTabular::VALIGN_MIDDLE:
852                         status.setOnOff(
853                                 tabular.getVAlignment(cur.idx(), flag) == LyXTabular::LYX_VALIGN_MIDDLE);
854                         break;
855
856                 case LyXTabular::SET_LONGTABULAR:
857                         status.setOnOff(tabular.isLongTabular());
858                         break;
859
860                 case LyXTabular::UNSET_LONGTABULAR:
861                         status.setOnOff(!tabular.isLongTabular());
862                         break;
863
864                 case LyXTabular::SET_ROTATE_TABULAR:
865                         status.setOnOff(tabular.getRotateTabular());
866                         break;
867
868                 case LyXTabular::UNSET_ROTATE_TABULAR:
869                         status.setOnOff(!tabular.getRotateTabular());
870                         break;
871
872                 case LyXTabular::SET_ROTATE_CELL:
873                         status.setOnOff(tabular.getRotateCell(cur.idx()));
874                         break;
875
876                 case LyXTabular::UNSET_ROTATE_CELL:
877                         status.setOnOff(!tabular.getRotateCell(cur.idx()));
878                         break;
879
880                 case LyXTabular::SET_USEBOX:
881                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
882                         break;
883
884                 case LyXTabular::SET_LTFIRSTHEAD:
885                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
886                         break;
887
888                 case LyXTabular::SET_LTHEAD:
889                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
890                         break;
891
892                 case LyXTabular::SET_LTFOOT:
893                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
894                         break;
895
896                 case LyXTabular::SET_LTLASTFOOT:
897                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
898                         break;
899
900                 case LyXTabular::SET_LTNEWPAGE:
901                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
902                         break;
903
904                 default:
905                         status.clear();
906                         status.enabled(false);
907                         break;
908                 }
909                 return true;
910         }
911
912         default:
913                 // we try to handle this event in the insets dispatch function.
914                 return cell(cur.idx())->getStatus(cur, cmd, status);
915         }
916 }
917
918
919 int InsetTabular::latex(Buffer const & buf, ostream & os,
920                         OutputParams const & runparams) const
921 {
922         return tabular.latex(buf, os, runparams);
923 }
924
925
926 int InsetTabular::plaintext(Buffer const & buf, ostream & os,
927                         OutputParams const & runparams) const
928 {
929         int const dp = runparams.linelen ? runparams.depth : 0;
930         return tabular.plaintext(buf, os, runparams, dp, false, 0);
931 }
932
933
934 int InsetTabular::linuxdoc(Buffer const & buf, ostream & os,
935                            OutputParams const & runparams) const
936 {
937         return tabular.linuxdoc(buf,os, runparams);
938 }
939
940
941 int InsetTabular::docbook(Buffer const & buf, ostream & os,
942                           OutputParams const & runparams) const
943 {
944         int ret = 0;
945         InsetBase * master = 0;
946
947 #ifdef WITH_WARNINGS
948 #warning Why not pass a proper DocIterator here?
949 #endif
950 #if 0
951         // if the table is inside a float it doesn't need the informaltable
952         // wrapper. Search for it.
953         for (master = owner(); master; master = master->owner())
954                 if (master->lyxCode() == InsetBase::FLOAT_CODE)
955                         break;
956 #endif
957
958         if (!master) {
959                 os << "<informaltable>";
960                 ++ret;
961         }
962         ret += tabular.docbook(buf, os, runparams);
963         if (!master) {
964                 os << "</informaltable>";
965                 ++ret;
966         }
967         return ret;
968 }
969
970
971 void InsetTabular::validate(LaTeXFeatures & features) const
972 {
973         tabular.validate(features);
974 }
975
976
977 shared_ptr<InsetText const> InsetTabular::cell(idx_type idx) const
978 {
979         return tabular.getCellInset(idx);
980 }
981
982
983 shared_ptr<InsetText> InsetTabular::cell(idx_type idx)
984 {
985         return tabular.getCellInset(idx);
986 }
987
988
989 void InsetTabular::getCursorPos(CursorSlice const & sl, int & x, int & y) const
990 {
991         cell(sl.idx())->getCursorPos(sl, x, y);
992
993         // y offset     correction
994         int const row = tabular.row_of_cell(sl.idx());
995         for (int i = 0; i <= row; ++i) {
996                 if (i != 0) {
997                         y += tabular.getAscentOfRow(i);
998                         y += tabular.getAdditionalHeight(i);
999                 }
1000                 if (i != row)
1001                         y += tabular.getDescentOfRow(i);
1002         }
1003
1004         // x offset correction
1005         int const col = tabular.column_of_cell(sl.idx());
1006         int idx = tabular.getCellNumber(row, 0);
1007         for (int j = 0; j < col; ++j) {
1008                 if (tabular.isPartOfMultiColumn(row, j))
1009                         continue;
1010                 x += tabular.getWidthOfColumn(idx);
1011                 ++idx;
1012         }
1013         x += tabular.getBeginningOfTextInCell(idx);
1014         x += ADD_TO_TABULAR_WIDTH;
1015         x += scroll();
1016 }
1017
1018
1019 namespace  {
1020
1021
1022 // Manhattan distance to nearest corner
1023 int dist(InsetOld const & inset, int x, int y)
1024 {
1025         int xx = 0;
1026         int yy = 0;
1027         Point o = theCoords.insets_.xy(&inset);
1028         int const xo = o.x_;
1029         int const yo = o.y_;
1030
1031         if (x < xo)
1032                 xx = xo - x;
1033         else if (x > xo + inset.width())
1034                 xx = x - xo - inset.width();
1035
1036         if (y < yo - inset.ascent())
1037                 yy = yo - inset.ascent() - y;
1038         else if (y > yo + inset.descent())
1039                 yy = y - yo - inset.descent();
1040
1041         lyxerr << " xo_=" << xo << "  yo_=" << yo
1042                << " width_=" << inset.width() << " ascent=" << inset.ascent()
1043                << " descent=" << inset.descent()
1044                << " dist=" << xx + yy << endl;
1045         return xx + yy;
1046 }
1047
1048
1049 } //namespace anon
1050
1051
1052 InsetBase * InsetTabular::setPos(LCursor & cur, int x, int y) const
1053 {
1054         lyxerr << "# InsetTabular::setPos()  x=" << x << " y=" << y << endl;
1055         idx_type idx_min = 0;
1056         int dist_min = std::numeric_limits<int>::max();
1057         for (idx_type i = 0; i < nargs(); ++i) {
1058                 if (theCoords.insets_.has(tabular.getCellInset(i).get())) {
1059                         int d = dist(*tabular.getCellInset(i), x, y);
1060                         if (d < dist_min) {
1061                                 dist_min = d;
1062                                 idx_min = i;
1063                         }
1064                 }
1065         }
1066         cur.idx() = idx_min;
1067         //lyxerr << "# InsetTabular::setPos()\n" << cur << endl;
1068         resetPos(cur);
1069         return cell(cur.idx())->text_.editXY(cur, x, y);
1070 }
1071
1072
1073 int InsetTabular::getCellXPos(idx_type const cell) const
1074 {
1075         idx_type c = cell;
1076
1077         for (; !tabular.isFirstCellInRow(c); --c)
1078                 ;
1079         int lx = tabular.getWidthOfColumn(cell);
1080         for (; c < cell; ++c)
1081                 lx += tabular.getWidthOfColumn(c);
1082
1083         return lx - tabular.getWidthOfColumn(cell);
1084 }
1085
1086
1087 void InsetTabular::resetPos(LCursor & cur) const
1088 {
1089         BufferView & bv = cur.bv();
1090 //      col_type const actcol = tabular.column_of_cell(cur.idx());
1091 //      int const offset = ADD_TO_TABULAR_WIDTH + 2;
1092 //      int const new_x = getCellXPos(cur.idx()) + offset;
1093 //      int const old_x = cursorx_;
1094 //      int const col_width = tabular.getWidthOfColumn(cur.idx());
1095 //      cursorx_ = new_x;
1096 //    cursor.x(getCellXPos(cur.idx()) + offset);
1097 //      if (actcol < tabular.columns() - 1 && scroll(false) &&
1098 //              tabular.getWidthOfTabular() < bv.workWidth()-20)
1099 //      {
1100 //              scroll(bv, 0.0F);
1101 //      } else if (cursorx_ - offset > 20 &&
1102 //                 cursorx_ - offset + col_width > bv.workWidth() - 20) {
1103 //              scroll(bv, - col_width - 20);
1104 //      } else if (cursorx_ - offset < 20) {
1105 //              scroll(bv, 20 - cursorx_ + offset);
1106 //      } else if (scroll() && xo() > 20 &&
1107 //                 xo() + tabular.getWidthOfTabular() > bv.workWidth() - 20) {
1108 //              scroll(bv, old_x - cursorx_);
1109 //      }
1110
1111         if (&cur.inset() != this) {
1112                 scroll(bv, 0.0F);
1113         } else {
1114                 int const X1 = 0;
1115                 int const X2 = bv.workWidth();
1116                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
1117                 int const x1 = xo() + scroll() + getCellXPos(cur.idx()) + offset;
1118                 int const x2 = x1 + tabular.getWidthOfColumn(cur.idx());
1119
1120                 if (x1 < X1)
1121                         scroll(bv, X1 + 20 - x1);
1122                 else if (x2 > X2)
1123                         scroll(bv, X2 - 20 - x2);
1124         }
1125
1126         cur.needsUpdate();
1127
1128         InsetTabularMailer(*this).updateDialog(&bv);
1129 }
1130
1131
1132 void InsetTabular::moveNextCell(LCursor & cur)
1133 {
1134         lyxerr << "InsetTabular::moveNextCell 1 cur: " << cur.top() << endl;
1135         if (isRightToLeft(cur)) {
1136                 lyxerr << "InsetTabular::moveNextCell A cur: " << endl;
1137                 if (tabular.isFirstCellInRow(cur.idx())) {
1138                         row_type const row = tabular.row_of_cell(cur.idx());
1139                         if (row == tabular.rows() - 1)
1140                                 return;
1141                         cur.idx() = tabular.getCellBelow(tabular.getLastCellInRow(row));
1142                 } else {
1143                         if (cur.idx() == 0)
1144                                 return;
1145                         --cur.idx();
1146                 }
1147         } else {
1148                 lyxerr << "InsetTabular::moveNextCell B cur: " << endl;
1149                 if (tabular.isLastCell(cur.idx()))
1150                         return;
1151                 ++cur.idx();
1152         }
1153         cur.pit() = 0;
1154         cur.pos() = 0;
1155         lyxerr << "InsetTabular::moveNextCell 2 cur: " << cur.top() << endl;
1156         resetPos(cur);
1157 }
1158
1159
1160 void InsetTabular::movePrevCell(LCursor & cur)
1161 {
1162         if (isRightToLeft(cur)) {
1163                 if (tabular.isLastCellInRow(cur.idx())) {
1164                         row_type const row = tabular.row_of_cell(cur.idx());
1165                         if (row == 0)
1166                                 return;
1167                         cur.idx() = tabular.getFirstCellInRow(row);
1168                         cur.idx() = tabular.getCellAbove(cur.idx());
1169                 } else {
1170                         if (tabular.isLastCell(cur.idx()))
1171                                 return;
1172                         ++cur.idx();
1173                 }
1174         } else {
1175                 if (cur.idx() == 0) // first cell
1176                         return;
1177                 --cur.idx();
1178         }
1179         cur.pit() = 0;
1180         cur.pos() = 0;
1181         resetPos(cur);
1182 }
1183
1184
1185 bool InsetTabular::tabularFeatures(LCursor & cur, string const & what)
1186 {
1187         LyXTabular::Feature action = LyXTabular::LAST_ACTION;
1188
1189         int i = 0;
1190         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
1191                 string const tmp = tabularFeature[i].feature;
1192
1193                 if (tmp == what.substr(0, tmp.length())) {
1194                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
1195                         //tabularFeatures[i].feature.length())) {
1196                         action = tabularFeature[i].action;
1197                         break;
1198                 }
1199         }
1200         if (action == LyXTabular::LAST_ACTION)
1201                 return false;
1202
1203         string const val =
1204                 ltrim(what.substr(tabularFeature[i].feature.length()));
1205         tabularFeatures(cur, action, val);
1206         return true;
1207 }
1208
1209
1210 namespace {
1211
1212 void checkLongtableSpecial(LyXTabular::ltType & ltt,
1213                           string const & special, bool & flag)
1214 {
1215         if (special == "dl_above") {
1216                 ltt.topDL = flag;
1217                 ltt.set = false;
1218         } else if (special == "dl_below") {
1219                 ltt.bottomDL = flag;
1220                 ltt.set = false;
1221         } else if (special == "empty") {
1222                 ltt.empty = flag;
1223                 ltt.set = false;
1224         } else if (flag) {
1225                 ltt.empty = false;
1226                 ltt.set = true;
1227         }
1228 }
1229
1230 } // anon namespace
1231
1232
1233 void InsetTabular::tabularFeatures(LCursor & cur,
1234         LyXTabular::Feature feature, string const & value)
1235 {
1236         BufferView & bv = cur.bv();
1237         col_type sel_col_start;
1238         col_type sel_col_end;
1239         row_type sel_row_start;
1240         row_type sel_row_end;
1241         bool setLines = false;
1242         LyXAlignment setAlign = LYX_ALIGN_LEFT;
1243         LyXTabular::VAlignment setVAlign = LyXTabular::LYX_VALIGN_TOP;
1244
1245         switch (feature) {
1246
1247         case LyXTabular::M_ALIGN_LEFT:
1248         case LyXTabular::ALIGN_LEFT:
1249                 setAlign = LYX_ALIGN_LEFT;
1250                 break;
1251
1252         case LyXTabular::M_ALIGN_RIGHT:
1253         case LyXTabular::ALIGN_RIGHT:
1254                 setAlign = LYX_ALIGN_RIGHT;
1255                 break;
1256
1257         case LyXTabular::M_ALIGN_CENTER:
1258         case LyXTabular::ALIGN_CENTER:
1259                 setAlign = LYX_ALIGN_CENTER;
1260                 break;
1261
1262         case LyXTabular::ALIGN_BLOCK:
1263                 setAlign = LYX_ALIGN_BLOCK;
1264                 break;
1265
1266         case LyXTabular::M_VALIGN_TOP:
1267         case LyXTabular::VALIGN_TOP:
1268                 setVAlign = LyXTabular::LYX_VALIGN_TOP;
1269                 break;
1270
1271         case LyXTabular::M_VALIGN_BOTTOM:
1272         case LyXTabular::VALIGN_BOTTOM:
1273                 setVAlign = LyXTabular::LYX_VALIGN_BOTTOM;
1274                 break;
1275
1276         case LyXTabular::M_VALIGN_MIDDLE:
1277         case LyXTabular::VALIGN_MIDDLE:
1278                 setVAlign = LyXTabular::LYX_VALIGN_MIDDLE;
1279                 break;
1280
1281         default:
1282                 break;
1283         }
1284
1285         recordUndo(cur, Undo::ATOMIC);
1286
1287         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1288         row_type const row = tabular.row_of_cell(cur.idx());
1289         col_type const column = tabular.column_of_cell(cur.idx());
1290         bool flag = true;
1291         LyXTabular::ltType ltt;
1292
1293         switch (feature) {
1294
1295         case LyXTabular::SET_PWIDTH: {
1296                 LyXLength const len(value);
1297                 tabular.setColumnPWidth(cur.idx(), len);
1298                 if (len.zero()
1299                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
1300                         tabularFeatures(cur, LyXTabular::ALIGN_CENTER, string());
1301                 else if (!len.zero()
1302                          && tabular.getAlignment(cur.idx(), true) != LYX_ALIGN_BLOCK)
1303                         tabularFeatures(cur, LyXTabular::ALIGN_BLOCK, string());
1304                 break;
1305         }
1306
1307         case LyXTabular::SET_MPWIDTH:
1308                 tabular.setMColumnPWidth(cur.idx(), LyXLength(value));
1309                 break;
1310
1311         case LyXTabular::SET_SPECIAL_COLUMN:
1312         case LyXTabular::SET_SPECIAL_MULTI:
1313                 tabular.setAlignSpecial(cur.idx(),value,feature);
1314                 break;
1315
1316         case LyXTabular::APPEND_ROW:
1317                 // append the row into the tabular
1318                 tabular.appendRow(bv.buffer()->params(), cur.idx());
1319                 break;
1320
1321         case LyXTabular::APPEND_COLUMN:
1322                 // append the column into the tabular
1323                 tabular.appendColumn(bv.buffer()->params(), cur.idx());
1324                 break;
1325
1326         case LyXTabular::DELETE_ROW:
1327                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1328                         tabular.deleteRow(sel_row_start);
1329                 if (sel_row_start >= tabular.rows())
1330                         --sel_row_start;
1331                 cur.idx() = tabular.getCellNumber(sel_row_start, column);
1332                 cur.pit() = 0;
1333                 cur.pos() = 0;
1334                 cur.selection() = false;
1335                 break;
1336
1337         case LyXTabular::DELETE_COLUMN:
1338                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
1339                         tabular.deleteColumn(sel_col_start);
1340                 if (sel_col_start >= tabular.columns())
1341                         --sel_col_start;
1342                 cur.idx() = tabular.getCellNumber(row, sel_col_start);
1343                 cur.pit() = 0;
1344                 cur.pos() = 0;
1345                 cur.selection() = false;
1346                 break;
1347
1348         case LyXTabular::M_TOGGLE_LINE_TOP:
1349                 flag = false;
1350         case LyXTabular::TOGGLE_LINE_TOP: {
1351                 bool lineSet = !tabular.topLine(cur.idx(), flag);
1352                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1353                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1354                                 tabular.setTopLine(
1355                                         tabular.getCellNumber(i, j),
1356                                         lineSet, flag);
1357                 break;
1358         }
1359
1360         case LyXTabular::M_TOGGLE_LINE_BOTTOM:
1361                 flag = false;
1362         case LyXTabular::TOGGLE_LINE_BOTTOM: {
1363                 bool lineSet = !tabular.bottomLine(cur.idx(), flag);
1364                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1365                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1366                                 tabular.setBottomLine(
1367                                         tabular.getCellNumber(i, j),
1368                                         lineSet,
1369                                         flag);
1370                 break;
1371         }
1372
1373         case LyXTabular::M_TOGGLE_LINE_LEFT:
1374                 flag = false;
1375         case LyXTabular::TOGGLE_LINE_LEFT: {
1376                 bool lineSet = !tabular.leftLine(cur.idx(), flag);
1377                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1378                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1379                                 tabular.setLeftLine(
1380                                         tabular.getCellNumber(i,j),
1381                                         lineSet,
1382                                         flag);
1383                 break;
1384         }
1385
1386         case LyXTabular::M_TOGGLE_LINE_RIGHT:
1387                 flag = false;
1388         case LyXTabular::TOGGLE_LINE_RIGHT: {
1389                 bool lineSet = !tabular.rightLine(cur.idx(), flag);
1390                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1391                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1392                                 tabular.setRightLine(
1393                                         tabular.getCellNumber(i,j),
1394                                         lineSet,
1395                                         flag);
1396                 break;
1397         }
1398
1399         case LyXTabular::M_ALIGN_LEFT:
1400         case LyXTabular::M_ALIGN_RIGHT:
1401         case LyXTabular::M_ALIGN_CENTER:
1402                 flag = false;
1403         case LyXTabular::ALIGN_LEFT:
1404         case LyXTabular::ALIGN_RIGHT:
1405         case LyXTabular::ALIGN_CENTER:
1406         case LyXTabular::ALIGN_BLOCK:
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.setAlignment(
1410                                         tabular.getCellNumber(i, j),
1411                                         setAlign,
1412                                         flag);
1413                 break;
1414
1415         case LyXTabular::M_VALIGN_TOP:
1416         case LyXTabular::M_VALIGN_BOTTOM:
1417         case LyXTabular::M_VALIGN_MIDDLE:
1418                 flag = false;
1419         case LyXTabular::VALIGN_TOP:
1420         case LyXTabular::VALIGN_BOTTOM:
1421         case LyXTabular::VALIGN_MIDDLE:
1422                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1423                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1424                                 tabular.setVAlignment(
1425                                         tabular.getCellNumber(i, j),
1426                                         setVAlign, flag);
1427                 break;
1428
1429         case LyXTabular::MULTICOLUMN: {
1430                 if (sel_row_start != sel_row_end) {
1431 #ifdef WITH_WARNINGS
1432 #warning Need I say it ? This is horrible.
1433 #endif
1434                         Alert::error(_("Error setting multicolumn"),
1435                                    _("You cannot set multicolumn vertically."));
1436                         return;
1437                 }
1438                 if (!cur.selection()) {
1439                         // just multicol for one single cell
1440                         // check whether we are completely in a multicol
1441                         if (tabular.isMultiColumn(cur.idx()))
1442                                 tabular.unsetMultiColumn(cur.idx());
1443                         else
1444                                 tabular.setMultiColumn(bv.buffer(), cur.idx(), 1);
1445                         break;
1446                 }
1447                 // we have a selection so this means we just add all this
1448                 // cells to form a multicolumn cell
1449                 idx_type const s_start = cur.selBegin().idx();
1450                 idx_type const s_end = cur.selEnd().idx();
1451                 tabular.setMultiColumn(bv.buffer(), s_start, s_end - s_start + 1);
1452                 cur.idx() = s_start;
1453                 cur.pit() = 0;
1454                 cur.pos() = 0;
1455                 cur.selection() = false;
1456                 break;
1457         }
1458
1459         case LyXTabular::SET_ALL_LINES:
1460                 setLines = true;
1461         case LyXTabular::UNSET_ALL_LINES:
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                 break;
1467
1468         case LyXTabular::SET_LONGTABULAR:
1469                 tabular.setLongTabular(true);
1470                 break;
1471
1472         case LyXTabular::UNSET_LONGTABULAR:
1473                 tabular.setLongTabular(false);
1474                 break;
1475
1476         case LyXTabular::SET_ROTATE_TABULAR:
1477                 tabular.setRotateTabular(true);
1478                 break;
1479
1480         case LyXTabular::UNSET_ROTATE_TABULAR:
1481                 tabular.setRotateTabular(false);
1482                 break;
1483
1484         case LyXTabular::SET_ROTATE_CELL:
1485                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1486                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1487                                 tabular.setRotateCell(
1488                                         tabular.getCellNumber(i, j), true);
1489                 break;
1490
1491         case LyXTabular::UNSET_ROTATE_CELL:
1492                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1493                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1494                                 tabular.setRotateCell(
1495                                         tabular.getCellNumber(i, j), false);
1496                 break;
1497
1498         case LyXTabular::SET_USEBOX: {
1499                 LyXTabular::BoxType val = LyXTabular::BoxType(convert<int>(value));
1500                 if (val == tabular.getUsebox(cur.idx()))
1501                         val = LyXTabular::BOX_NONE;
1502                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
1503                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
1504                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1505                 break;
1506         }
1507
1508         case LyXTabular::UNSET_LTFIRSTHEAD:
1509                 flag = false;
1510         case LyXTabular::SET_LTFIRSTHEAD:
1511                 tabular.getRowOfLTFirstHead(row, ltt);
1512                 checkLongtableSpecial(ltt, value, flag);
1513                 tabular.setLTHead(row, flag, ltt, true);
1514                 break;
1515
1516         case LyXTabular::UNSET_LTHEAD:
1517                 flag = false;
1518         case LyXTabular::SET_LTHEAD:
1519                 tabular.getRowOfLTHead(row, ltt);
1520                 checkLongtableSpecial(ltt, value, flag);
1521                 tabular.setLTHead(row, flag, ltt, false);
1522                 break;
1523
1524         case LyXTabular::UNSET_LTFOOT:
1525                 flag = false;
1526         case LyXTabular::SET_LTFOOT:
1527                 tabular.getRowOfLTFoot(row, ltt);
1528                 checkLongtableSpecial(ltt, value, flag);
1529                 tabular.setLTFoot(row, flag, ltt, false);
1530                 break;
1531
1532         case LyXTabular::UNSET_LTLASTFOOT:
1533                 flag = false;
1534         case LyXTabular::SET_LTLASTFOOT:
1535                 tabular.getRowOfLTLastFoot(row, ltt);
1536                 checkLongtableSpecial(ltt, value, flag);
1537                 tabular.setLTFoot(row, flag, ltt, true);
1538                 break;
1539
1540         case LyXTabular::SET_LTNEWPAGE:
1541                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1542                 break;
1543
1544         // dummy stuff just to avoid warnings
1545         case LyXTabular::LAST_ACTION:
1546                 break;
1547         }
1548
1549         InsetTabularMailer(*this).updateDialog(&bv);
1550 }
1551
1552
1553 bool InsetTabular::showInsetDialog(BufferView * bv) const
1554 {
1555         InsetTabularMailer(*this).showDialog(bv);
1556         return true;
1557 }
1558
1559
1560 void InsetTabular::openLayoutDialog(BufferView * bv) const
1561 {
1562         InsetTabularMailer(*this).showDialog(bv);
1563 }
1564
1565
1566 void InsetTabular::getLabelList(Buffer const & buffer,
1567                                 vector<string> & list) const
1568 {
1569         tabular.getLabelList(buffer, list);
1570 }
1571
1572
1573 bool InsetTabular::copySelection(LCursor & cur)
1574 {
1575         if (!cur.selection())
1576                 return false;
1577
1578         row_type rs, re;
1579         col_type cs, ce;
1580         getSelection(cur, rs, re, cs, ce);
1581
1582         paste_tabular.reset(new LyXTabular(tabular));
1583
1584         for (row_type i = 0; i < rs; ++i)
1585                 paste_tabular->deleteRow(0);
1586
1587         row_type const rows = re - rs + 1;
1588         while (paste_tabular->rows() > rows)
1589                 paste_tabular->deleteRow(rows);
1590
1591         paste_tabular->setTopLine(0, true, true);
1592         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
1593                                      true, true);
1594
1595         for (col_type i = 0; i < cs; ++i)
1596                 paste_tabular->deleteColumn(0);
1597
1598         col_type const columns = ce - cs + 1;
1599         while (paste_tabular->columns() > columns)
1600                 paste_tabular->deleteColumn(columns);
1601
1602         paste_tabular->setLeftLine(0, true, true);
1603         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
1604                                     true, true);
1605
1606         ostringstream os;
1607         OutputParams const runparams;
1608         paste_tabular->plaintext(cur.buffer(), os, runparams, 0, true, '\t');
1609         cur.bv().stuffClipboard(os.str());
1610         return true;
1611 }
1612
1613
1614 bool InsetTabular::pasteSelection(LCursor & cur)
1615 {
1616         if (!paste_tabular)
1617                 return false;
1618         col_type const actcol = tabular.column_of_cell(cur.idx());
1619         row_type const actrow = tabular.row_of_cell(cur.idx());
1620         for (row_type r1 = 0, r2 = actrow;
1621              r1 < paste_tabular->rows() && r2 < tabular.rows();
1622              ++r1, ++r2) {
1623                 for (col_type c1 = 0, c2 = actcol;
1624                     c1 < paste_tabular->columns() && c2 < tabular.columns();
1625                     ++c1, ++c2) {
1626                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
1627                             tabular.isPartOfMultiColumn(r2, c2))
1628                                 continue;
1629                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
1630                                 --c2;
1631                                 continue;
1632                         }
1633                         if (tabular.isPartOfMultiColumn(r2, c2)) {
1634                                 --c1;
1635                                 continue;
1636                         }
1637                         shared_ptr<InsetText> inset = tabular.getCellInset(r2, c2);
1638                         inset = paste_tabular->getCellInset(r1, c1);
1639                         inset->markNew();
1640                 }
1641         }
1642         return true;
1643 }
1644
1645
1646 void InsetTabular::cutSelection(LCursor & cur)
1647 {
1648         if (!cur.selection())
1649                 return;
1650
1651         bool const track = cur.buffer().params().tracking_changes;
1652         row_type rs, re;
1653         col_type cs, ce;
1654         getSelection(cur, rs, re, cs, ce);
1655         for (row_type i = rs; i <= re; ++i)
1656                 for (col_type j = cs; j <= ce; ++j)
1657                         cell(tabular.getCellNumber(i, j))->clear(track);
1658
1659         // cursor position might be invalid now
1660         cur.pos() = cur.lastpos();
1661         cur.clearSelection();
1662 }
1663
1664
1665 bool InsetTabular::isRightToLeft(LCursor & cur) const
1666 {
1667         BOOST_ASSERT(cur.size() > 1);
1668         Paragraph const & parentpar = cur[cur.size() - 2].paragraph();
1669         LCursor::pos_type const parentpos = cur[cur.size() - 2].pos();
1670         return parentpar.getFontSettings(cur.bv().buffer()->params(),
1671                                          parentpos).language()->RightToLeft();
1672 }
1673
1674
1675 void InsetTabular::getSelection(LCursor & cur,
1676         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
1677 {
1678         CursorSlice const & beg = cur.selBegin();
1679         CursorSlice const & end = cur.selEnd();
1680         cs = tabular.column_of_cell(beg.idx());
1681         ce = tabular.column_of_cell(end.idx());
1682         if (cs > ce) {
1683                 ce = cs;
1684                 cs = tabular.column_of_cell(end.idx());
1685         } else {
1686                 ce = tabular.right_column_of_cell(end.idx());
1687         }
1688
1689         rs = tabular.row_of_cell(beg.idx());
1690         re = tabular.row_of_cell(end.idx());
1691         if (rs > re)
1692                 swap(rs, re);
1693 }
1694
1695
1696 size_t InsetTabular::nargs() const
1697 {
1698         return tabular.getNumberOfCells();
1699 }
1700
1701
1702 LyXText * InsetTabular::getText(int idx) const
1703 {
1704         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
1705 }
1706
1707
1708 void InsetTabular::markErased()
1709 {
1710         for (idx_type idx = 0; idx < nargs(); ++idx)
1711                 cell(idx)->markErased();
1712 }
1713
1714
1715 bool InsetTabular::forceDefaultParagraphs(InsetBase const *) const
1716 {
1717 #if 0
1718         idx_type const cell = tabular.getCellFromInset(in);
1719         // FIXME: getCellFromInset() returns now always a valid cell, so
1720         // the stuff below can be deleted, and instead we have:
1721         return tabular.getPWidth(cell).zero();
1722
1723         if (cell != npos)
1724                 return tabular.getPWidth(cell).zero();
1725
1726         // this is a workaround for a crash (New, Insert->Tabular,
1727         // Insert->FootNote)
1728         if (!owner())
1729                 return false;
1730
1731         // well we didn't obviously find it so maybe our owner knows more
1732         BOOST_ASSERT(owner());
1733         return owner()->forceDefaultParagraphs(in);
1734 #endif
1735         return false;
1736 }
1737
1738
1739 bool InsetTabular::insertAsciiString(BufferView & bv, string const & buf,
1740                                      bool usePaste)
1741 {
1742         if (buf.length() <= 0)
1743                 return true;
1744
1745         col_type cols = 1;
1746         row_type rows = 1;
1747         col_type maxCols = 1;
1748         string::size_type const len = buf.length();
1749         string::size_type p = 0;
1750
1751         while (p < len && (p = buf.find_first_of("\t\n", p)) != string::npos) {
1752                 switch (buf[p]) {
1753                 case '\t':
1754                         ++cols;
1755                         break;
1756                 case '\n':
1757                         if (p + 1 < len)
1758                                 ++rows;
1759                         maxCols = max(cols, maxCols);
1760                         cols = 1;
1761                         break;
1762                 }
1763                 ++p;
1764         }
1765         maxCols = max(cols, maxCols);
1766         LyXTabular * loctab;
1767         idx_type cell = 0;
1768         col_type ocol = 0;
1769         row_type row = 0;
1770         if (usePaste) {
1771                 paste_tabular.reset(
1772                         new LyXTabular(bv.buffer()->params(), rows, maxCols));
1773                 loctab = paste_tabular.get();
1774                 cols = 0;
1775         } else {
1776                 loctab = &tabular;
1777                 cell = bv.cursor().idx();
1778                 ocol = tabular.column_of_cell(cell);
1779                 row = tabular.row_of_cell(cell);
1780         }
1781
1782         string::size_type op = 0;
1783         idx_type const cells = loctab->getNumberOfCells();
1784         p = 0;
1785         cols = ocol;
1786         rows = loctab->rows();
1787         col_type const columns = loctab->columns();
1788
1789         while (cell < cells && p < len && row < rows &&
1790                (p = buf.find_first_of("\t\n", p)) != string::npos)
1791         {
1792                 if (p >= len)
1793                         break;
1794                 switch (buf[p]) {
1795                 case '\t':
1796                         // we can only set this if we are not too far right
1797                         if (cols < columns) {
1798                                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
1799                                 Paragraph & par = inset->text_.getPar(0);
1800                                 LyXFont const font = inset->text_.getFont(par, 0);
1801                                 inset->setText(buf.substr(op, p - op), font);
1802                                 ++cols;
1803                                 ++cell;
1804                         }
1805                         break;
1806                 case '\n':
1807                         // we can only set this if we are not too far right
1808                         if (cols < columns) {
1809                                 shared_ptr<InsetText> inset = tabular.getCellInset(cell);
1810                                 Paragraph & par = inset->text_.getPar(0);
1811                                 LyXFont const font = inset->text_.getFont(par, 0);
1812                                 inset->setText(buf.substr(op, p - op), font);
1813                         }
1814                         cols = ocol;
1815                         ++row;
1816                         if (row < rows)
1817                                 cell = loctab->getCellNumber(row, cols);
1818                         break;
1819                 }
1820                 ++p;
1821                 op = p;
1822         }
1823         // check for the last cell if there is no trailing '\n'
1824         if (cell < cells && op < len) {
1825                 shared_ptr<InsetText> inset = loctab->getCellInset(cell);
1826                 Paragraph & par = inset->text_.getPar(0);
1827                 LyXFont const font = inset->text_.getFont(par, 0);
1828                 inset->setText(buf.substr(op, len - op), font);
1829         }
1830         return true;
1831 }
1832
1833
1834 void InsetTabular::addPreview(PreviewLoader & loader) const
1835 {
1836         row_type const rows = tabular.rows();
1837         col_type const columns = tabular.columns();
1838         for (row_type i = 0; i < rows; ++i) {
1839                 for (col_type j = 0; j < columns; ++j)
1840                         tabular.getCellInset(i, j)->addPreview(loader);
1841         }
1842 }
1843
1844
1845 bool InsetTabular::tablemode(LCursor & cur) const
1846 {
1847         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
1848 }
1849
1850
1851
1852
1853
1854 string const InsetTabularMailer::name_("tabular");
1855
1856 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
1857         : inset_(const_cast<InsetTabular &>(inset))
1858 {}
1859
1860
1861 string const InsetTabularMailer::inset2string(Buffer const &) const
1862 {
1863         return params2string(inset_);
1864 }
1865
1866
1867 void InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
1868 {
1869         istringstream data(in);
1870         LyXLex lex(0,0);
1871         lex.setStream(data);
1872
1873         if (in.empty())
1874                 return;
1875
1876         string token;
1877         lex >> token;
1878         if (!lex || token != name_)
1879                 return print_mailer_error("InsetTabularMailer", in, 1,
1880                                           name_);
1881
1882         // This is part of the inset proper that is usually swallowed
1883         // by Buffer::readInset
1884         lex >> token;
1885         if (!lex || token != "Tabular")
1886                 return print_mailer_error("InsetTabularMailer", in, 2,
1887                                           "Tabular");
1888
1889         Buffer const & buffer = inset.buffer();
1890         inset.read(buffer, lex);
1891 }
1892
1893
1894 string const InsetTabularMailer::params2string(InsetTabular const & inset)
1895 {
1896         ostringstream data;
1897         data << name_ << ' ';
1898         inset.write(inset.buffer(), data);
1899         data << "\\end_inset\n";
1900         return data.str();
1901 }