]> git.lyx.org Git - features.git/blob - src/insets/insettabular.C
38f0eb82966da70d2da964d38951909c0b3f01af
[features.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 "debug.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "FuncStatus.h"
22 #include "gettext.h"
23 #include "language.h"
24 #include "latexrunparams.h"
25 #include "LColor.h"
26 #include "lyx_cb.h"
27 #include "lyxlex.h"
28 #include "metricsinfo.h"
29 #include "paragraph.h"
30 #include "paragraph_funcs.h"
31 #include "ParagraphParameters.h"
32 #include "undo.h"
33
34 #include "frontends/Alert.h"
35 #include "frontends/font_metrics.h"
36 #include "frontends/LyXView.h"
37 #include "frontends/Painter.h"
38
39 #include "support/std_sstream.h"
40 #include <iostream>
41
42 using lyx::graphics::PreviewLoader;
43
44 using lyx::support::ltrim;
45 using lyx::support::strToInt;
46
47 using std::endl;
48 using std::max;
49 using std::swap;
50 using std::string;
51 using std::auto_ptr;
52 using std::istringstream;
53 using std::ostream;
54 using std::ostringstream;
55
56
57 namespace {
58
59 int const ADD_TO_HEIGHT = 2;
60 int const ADD_TO_TABULAR_WIDTH = 2;
61
62 ///
63 boost::scoped_ptr<LyXTabular> paste_tabular;
64
65
66 struct TabularFeature {
67         LyXTabular::Feature action;
68         string feature;
69 };
70
71
72 TabularFeature tabularFeature[] =
73 {
74         { LyXTabular::APPEND_ROW, "append-row" },
75         { LyXTabular::APPEND_COLUMN, "append-column" },
76         { LyXTabular::DELETE_ROW, "delete-row" },
77         { LyXTabular::DELETE_COLUMN, "delete-column" },
78         { LyXTabular::TOGGLE_LINE_TOP, "toggle-line-top" },
79         { LyXTabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
80         { LyXTabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
81         { LyXTabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
82         { LyXTabular::ALIGN_LEFT, "align-left" },
83         { LyXTabular::ALIGN_RIGHT, "align-right" },
84         { LyXTabular::ALIGN_CENTER, "align-center" },
85         { LyXTabular::ALIGN_BLOCK, "align-block" },
86         { LyXTabular::VALIGN_TOP, "valign-top" },
87         { LyXTabular::VALIGN_BOTTOM, "valign-bottom" },
88         { LyXTabular::VALIGN_MIDDLE, "valign-middle" },
89         { LyXTabular::M_TOGGLE_LINE_TOP, "m-toggle-line-top" },
90         { LyXTabular::M_TOGGLE_LINE_BOTTOM, "m-toggle-line-bottom" },
91         { LyXTabular::M_TOGGLE_LINE_LEFT, "m-toggle-line-left" },
92         { LyXTabular::M_TOGGLE_LINE_RIGHT, "m-toggle-line-right" },
93         { LyXTabular::M_ALIGN_LEFT, "m-align-left" },
94         { LyXTabular::M_ALIGN_RIGHT, "m-align-right" },
95         { LyXTabular::M_ALIGN_CENTER, "m-align-center" },
96         { LyXTabular::M_VALIGN_TOP, "m-valign-top" },
97         { LyXTabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
98         { LyXTabular::M_VALIGN_MIDDLE, "m-valign-middle" },
99         { LyXTabular::MULTICOLUMN, "multicolumn" },
100         { LyXTabular::SET_ALL_LINES, "set-all-lines" },
101         { LyXTabular::UNSET_ALL_LINES, "unset-all-lines" },
102         { LyXTabular::SET_LONGTABULAR, "set-longtabular" },
103         { LyXTabular::UNSET_LONGTABULAR, "unset-longtabular" },
104         { LyXTabular::SET_PWIDTH, "set-pwidth" },
105         { LyXTabular::SET_MPWIDTH, "set-mpwidth" },
106         { LyXTabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
107         { LyXTabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
108         { LyXTabular::SET_ROTATE_CELL, "set-rotate-cell" },
109         { LyXTabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
110         { LyXTabular::SET_USEBOX, "set-usebox" },
111         { LyXTabular::SET_LTHEAD, "set-lthead" },
112         { LyXTabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
113         { LyXTabular::SET_LTFOOT, "set-ltfoot" },
114         { LyXTabular::SET_LTLASTFOOT, "set-ltlastfoot" },
115         { LyXTabular::SET_LTNEWPAGE, "set-ltnewpage" },
116         { LyXTabular::SET_SPECIAL_COLUMN, "set-special-column" },
117         { LyXTabular::SET_SPECIAL_MULTI, "set-special-multi" },
118         { LyXTabular::LAST_ACTION, "" }
119 };
120
121 struct FindFeature {
122         FindFeature(LyXTabular::Feature feature) : feature_(feature) {}
123         bool operator()(TabularFeature & tf)
124         {
125                 return tf.action == feature_;
126         }
127 private:
128         LyXTabular::Feature feature_;
129 };
130
131 } // namespace anon
132
133
134 string const featureAsString(LyXTabular::Feature feature)
135 {
136         TabularFeature * it  = tabularFeature;
137         TabularFeature * end = it +
138                 sizeof(tabularFeature) / sizeof(TabularFeature);
139         it = std::find_if(it, end, FindFeature(feature));
140         return (it == end) ? string() : it->feature;
141 }
142
143
144 bool InsetTabular::hasPasteBuffer() const
145 {
146         return (paste_tabular.get() != 0);
147 }
148
149
150 InsetTabular::InsetTabular(Buffer const & buf, int rows, int columns)
151         : tabular(buf.params(), max(rows, 1), max(columns, 1)),
152           buffer_(&buf), cursorx_(0), cursory_(0)
153 {
154         tabular.setOwner(this);
155         // for now make it always display as display() inset
156         // just for test!!!
157         the_locking_inset = 0;
158         old_locking_inset = 0;
159         locked = false;
160         oldcell = -1;
161         actrow = actcell = 0;
162         clearSelection();
163         in_reset_pos = 0;
164         inset_x = 0;
165         inset_y = 0;
166 }
167
168
169 InsetTabular::InsetTabular(InsetTabular const & tab)
170         : UpdatableInset(tab), tabular(tab.tabular),
171                 buffer_(tab.buffer_), cursorx_(0), cursory_(0)
172 {
173         tabular.setOwner(this);
174         the_locking_inset = 0;
175         old_locking_inset = 0;
176         locked = false;
177         oldcell = -1;
178         actrow = actcell = 0;
179         clearSelection();
180         in_reset_pos = 0;
181         inset_x = 0;
182         inset_y = 0;
183 }
184
185
186 InsetTabular::~InsetTabular()
187 {
188         InsetTabularMailer(*this).hideDialog();
189 }
190
191
192 auto_ptr<InsetBase> InsetTabular::clone() const
193 {
194         return auto_ptr<InsetBase>(new InsetTabular(*this));
195 }
196
197
198 Buffer const & InsetTabular::buffer() const
199 {
200         return *buffer_;
201 }
202
203
204 BufferView * InsetTabular::view() const
205 {
206         BOOST_ASSERT(false);
207         return 0;
208 }
209
210
211 void InsetTabular::buffer(Buffer * b)
212 {
213         buffer_ = b;
214 }
215
216
217 void InsetTabular::write(Buffer const & buf, ostream & os) const
218 {
219         os << "Tabular" << endl;
220         tabular.write(buf, os);
221 }
222
223
224 void InsetTabular::read(Buffer const & buf, LyXLex & lex)
225 {
226         bool const old_format = (lex.getString() == "\\LyXTable");
227
228         tabular.read(buf, lex);
229
230         if (old_format)
231                 return;
232
233         lex.nextToken();
234         string token = lex.getString();
235         while (lex.isOK() && (token != "\\end_inset")) {
236                 lex.nextToken();
237                 token = lex.getString();
238         }
239         if (token != "\\end_inset") {
240                 lex.printError("Missing \\end_inset at this point. "
241                                "Read: `$$Token'");
242         }
243 }
244
245
246 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
247 {
248         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
249         //      mi.base.textwidth << "\n";
250         if (!mi.base.bv) {
251                 lyxerr << "InsetTabular::metrics: need bv" << endl;
252                 BOOST_ASSERT(false);
253         }
254
255         calculate_dimensions_of_cells(mi);
256
257         dim.asc = tabular.getAscentOfRow(0);
258         dim.des = tabular.getHeightOfTabular() - tabular.getAscentOfRow(0) + 1;
259         dim.wid = tabular.getWidthOfTabular() + 2 * ADD_TO_TABULAR_WIDTH;
260         dim_ = dim;
261 }
262
263
264 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
265 {
266         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
267
268         BufferView * bv = pi.base.bv;
269
270 #if 0
271         UpdatableInset::draw(pi, x, y);
272 #else
273         if (!owner())
274                 x += scroll();
275 #endif
276
277         top_x = x;
278         top_baseline = y;
279         x += ADD_TO_TABULAR_WIDTH;
280
281         int cell = 0;
282         first_visible_cell = -1;
283         for (int i = 0; i < tabular.rows(); ++i) {
284                 int nx = x;
285                 cell = tabular.getCellNumber(i, 0);
286                 if (y + tabular.getDescentOfRow(i) <= 0 &&
287                           y - tabular.getAscentOfRow(i) < pi.pain.paperHeight())
288                 {
289                         y += tabular.getDescentOfRow(i) +
290                                         tabular.getAscentOfRow(i + 1) +
291                                         tabular.getAdditionalHeight(i + 1);
292                         continue;
293                 }
294                 for (int j = 0; j < tabular.columns(); ++j) {
295                         if (nx > bv->workWidth())
296                                 break;
297                         if (tabular.isPartOfMultiColumn(i, j))
298                                 continue;
299                         int cx = nx + tabular.getBeginningOfTextInCell(cell);
300                         if (first_visible_cell < 0)
301                                 first_visible_cell = cell;
302                         if (hasSelection()) {
303                                 drawCellSelection(pi.pain, nx, y, i, j, cell);
304                         }
305
306                         tabular.getCellInset(cell).draw(pi, cx, y);
307                         drawCellLines(pi.pain, nx, y, i, cell);
308                         nx += tabular.getWidthOfColumn(cell);
309                         ++cell;
310                 }
311
312 // Would be nice, but for some completely unfathomable reason,
313 // on a col resize to a new fixed width, even though the insettexts
314 // are resized, the cell isn't, but drawing all cells in a tall table
315 // has the desired effect somehow. Complete dark magic.
316 #if 0
317                 // avoiding drawing the rest of a long table is
318                 // a pretty big speedup
319                 if (y > bv->workHeight())
320                         break;
321 #endif
322
323                 y += tabular.getDescentOfRow(i) +
324                         tabular.getAscentOfRow(i + 1) +
325                         tabular.getAdditionalHeight(i + 1);
326         }
327 }
328
329
330 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
331                                  int row, int cell) const
332 {
333         int x2 = x + tabular.getWidthOfColumn(cell);
334         bool on_off;
335
336         if (!tabular.topAlreadyDrawn(cell)) {
337                 on_off = !tabular.topLine(cell);
338                 pain.line(x, y - tabular.getAscentOfRow(row),
339                           x2, y -  tabular.getAscentOfRow(row),
340                           on_off ? LColor::tabularonoffline : LColor::tabularline,
341                           on_off ? Painter::line_onoffdash : Painter::line_solid);
342         }
343         on_off = !tabular.bottomLine(cell);
344         pain.line(x, y + tabular.getDescentOfRow(row),
345                   x2, y + tabular.getDescentOfRow(row),
346                   on_off ? LColor::tabularonoffline : LColor::tabularline,
347                   on_off ? Painter::line_onoffdash : Painter::line_solid);
348         if (!tabular.leftAlreadyDrawn(cell)) {
349                 on_off = !tabular.leftLine(cell);
350                 pain.line(x, y -  tabular.getAscentOfRow(row),
351                           x, y +  tabular.getDescentOfRow(row),
352                           on_off ? LColor::tabularonoffline : LColor::tabularline,
353                           on_off ? Painter::line_onoffdash : Painter::line_solid);
354         }
355         on_off = !tabular.rightLine(cell);
356         pain.line(x2 - tabular.getAdditionalWidth(cell),
357                   y -  tabular.getAscentOfRow(row),
358                   x2 - tabular.getAdditionalWidth(cell),
359                   y +  tabular.getDescentOfRow(row),
360                   on_off ? LColor::tabularonoffline : LColor::tabularline,
361                   on_off ? Painter::line_onoffdash : Painter::line_solid);
362 }
363
364
365 void InsetTabular::drawCellSelection(Painter & pain, int x, int y,
366                                      int row, int column, int cell) const
367 {
368         BOOST_ASSERT(hasSelection());
369         int cs = tabular.column_of_cell(sel_cell_start);
370         int ce = tabular.column_of_cell(sel_cell_end);
371         if (cs > ce) {
372                 ce = cs;
373                 cs = tabular.column_of_cell(sel_cell_end);
374         } else {
375                 ce = tabular.right_column_of_cell(sel_cell_end);
376         }
377
378         int rs = tabular.row_of_cell(sel_cell_start);
379         int re = tabular.row_of_cell(sel_cell_end);
380         if (rs > re)
381                 swap(rs, re);
382
383         if ((column >= cs) && (column <= ce) && (row >= rs) && (row <= re)) {
384                 int w = tabular.getWidthOfColumn(cell);
385                 int h = tabular.getAscentOfRow(row) + tabular.getDescentOfRow(row)-1;
386                 pain.fillRectangle(x, y - tabular.getAscentOfRow(row) + 1,
387                                    w, h, LColor::selection);
388         }
389 }
390
391
392 string const InsetTabular::editMessage() const
393 {
394         return _("Opened table");
395 }
396
397
398 void InsetTabular::insetUnlock(BufferView * bv)
399 {
400         if (the_locking_inset) {
401                 the_locking_inset->insetUnlock(bv);
402                 updateLocal(bv);
403                 the_locking_inset = 0;
404         }
405         actcell = 0;
406         oldcell = -1;
407         locked = false;
408         if (scroll(false) || hasSelection()) {
409                 clearSelection();
410                 if (scroll(false))
411                         scroll(bv, 0.0F);
412                 updateLocal(bv);
413         }
414 }
415
416
417 void InsetTabular::updateLocal(BufferView * bv) const
418 {
419         bv->updateInset(this);
420         if (locked)
421                 resetPos(bv);
422 }
423
424
425 bool InsetTabular::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
426 {
427         lyxerr[Debug::INSETTEXT] << "InsetTabular::LockInsetInInset("
428                               << inset << "): ";
429         if (!inset)
430                 return false;
431
432         oldcell = -1;
433
434         if (inset == &tabular.getCellInset(actcell)) {
435                 lyxerr[Debug::INSETTEXT] << "OK" << endl;
436                 the_locking_inset = &tabular.getCellInset(actcell);
437                 resetPos(bv);
438                 return true;
439         }
440
441         if (!the_locking_inset) {
442                 int const n = tabular.getNumberOfCells();
443                 for (int i = 0; i < n; ++i) {
444                         InsetText * in = &tabular.getCellInset(i);
445                         if (inset == in) {
446                                 actcell = i;
447                                 the_locking_inset = in;
448                                 locked = true;
449                                 resetPos(bv);
450                                 return true;
451                         }
452                         if (in->lockInsetInInset(bv, inset)) {
453                                 actcell = i;
454                                 the_locking_inset = in;
455                                 locked = true;
456                                 resetPos(bv);
457                                 in->dispatch(FuncRequest(bv, LFUN_INSET_EDIT));
458                                 return true;
459                         }
460                 }
461                 return false;
462         }
463
464         if (the_locking_inset && (the_locking_inset == inset)) {
465                 lyxerr[Debug::INSETTEXT] << "OK" << endl;
466                 resetPos(bv);
467                 return false;
468         }
469
470         if (the_locking_inset) {
471                 lyxerr[Debug::INSETTEXT] << "MAYBE" << endl;
472                 return the_locking_inset->lockInsetInInset(bv, inset);
473         }
474
475         lyxerr[Debug::INSETTEXT] << "NOT OK" << endl;
476         return false;
477 }
478
479
480 bool InsetTabular::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
481                                       bool lr)
482 {
483         if (!the_locking_inset)
484                 return false;
485         if (the_locking_inset == inset) {
486                 the_locking_inset->insetUnlock(bv);
487 #ifdef WITH_WARNINGS
488 #warning fix scrolling when cellinset has requested a scroll (Jug)!!!
489 #endif
490 #if 0
491                 if (scroll(false))
492                         scroll(bv, 0.0F);
493 #endif
494                 updateLocal(bv);
495                 // this has to be here otherwise we don't redraw the cell!
496                 the_locking_inset = 0;
497                 return true;
498         }
499         if (the_locking_inset->unlockInsetInInset(bv, inset, lr)) {
500                 if (inset->lyxCode() == TABULAR_CODE &&
501                     !the_locking_inset->getFirstLockingInsetOfType(TABULAR_CODE)) {
502                         InsetTabularMailer(*this).updateDialog(bv);
503                         oldcell = actcell;
504                 }
505                 return true;
506         }
507         return false;
508 }
509
510
511 int InsetTabular::insetInInsetY() const
512 {
513         if (!the_locking_inset)
514                 return 0;
515         return inset_y + the_locking_inset->insetInInsetY();
516 }
517
518
519 UpdatableInset * InsetTabular::getLockingInset() const
520 {
521         return the_locking_inset ? the_locking_inset->getLockingInset() :
522                 const_cast<InsetTabular *>(this);
523 }
524
525
526 UpdatableInset * InsetTabular::getFirstLockingInsetOfType(InsetOld::Code c)
527 {
528         if (c == lyxCode())
529                 return this;
530         if (the_locking_inset)
531                 return the_locking_inset->getFirstLockingInsetOfType(c);
532         return 0;
533 }
534
535
536 bool InsetTabular::insertInset(BufferView * bv, InsetOld * inset)
537 {
538         if (the_locking_inset)
539                 return the_locking_inset->insertInset(bv, inset);
540         return false;
541 }
542
543
544 void InsetTabular::lfunMousePress(FuncRequest const & cmd)
545 {
546         if (hasSelection() && cmd.button() == mouse_button::button3)
547                 return;
548
549         if (hasSelection()) {
550                 clearSelection();
551                 updateLocal(cmd.view());
552         }
553
554         int const ocell = actcell;
555         BufferView * bv = cmd.view();
556
557         if (!locked) {
558                 locked = true;
559                 the_locking_inset = 0;
560                 inset_x = 0;
561                 inset_y = 0;
562         }
563         setPos(bv, cmd.x, cmd.y);
564         clearSelection();
565
566         bool const inset_hit = insetHit(bv, cmd.x, cmd.y);
567
568         if (ocell == actcell && the_locking_inset && inset_hit) {
569                 resetPos(bv);
570                 FuncRequest cmd1 = cmd;
571                 cmd1.x -= inset_x;
572                 cmd1.y -= inset_y;
573                 the_locking_inset->dispatch(cmd1);
574                 return;
575         }
576
577         if (the_locking_inset) {
578                 the_locking_inset->insetUnlock(bv);
579                 updateLocal(bv);
580                 the_locking_inset = 0;
581         }
582
583         if (cmd.button() == mouse_button::button2) {
584                 dispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
585                 return;
586         }
587
588         if (inset_hit && bv->theLockingInset()) {
589                 if (!bv->lockInset(&tabular.getCellInset(actcell))) {
590                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
591                         return;
592                 }
593                 FuncRequest cmd1 = cmd;
594                 cmd1.x -= inset_x;
595                 cmd1.y -= inset_y;
596                 the_locking_inset->dispatch(cmd1);
597         }
598 }
599
600
601 bool InsetTabular::lfunMouseRelease(FuncRequest const & cmd)
602 {
603         DispatchResult ret(false);
604         if (the_locking_inset) {
605                 FuncRequest cmd1 = cmd;
606                 cmd1.x -= inset_x;
607                 cmd1.y -= inset_y;
608                 ret = the_locking_inset->dispatch(cmd1);
609         }
610         if (cmd.button() == mouse_button::button3 && ret == DispatchResult(false)) {
611                 InsetTabularMailer(*this).showDialog(cmd.view());
612                 return true;
613         }
614         return ret.dispatched() || ret.val() > FINISHED;
615 }
616
617
618 void InsetTabular::lfunMouseMotion(FuncRequest const & cmd)
619 {
620         if (the_locking_inset) {
621                 FuncRequest cmd1 = cmd;
622                 cmd1.x -= inset_x;
623                 cmd1.y -= inset_y;
624                 the_locking_inset->dispatch(cmd1);
625                 return;
626         }
627
628         BufferView * bv = cmd.view();
629         int const old_cell = actcell;
630
631         setPos(bv, cmd.x, cmd.y);
632         if (!hasSelection()) {
633                 setSelection(actcell, actcell);
634                 updateLocal(bv);
635         } else if (old_cell != actcell) {
636                 setSelection(sel_cell_start, actcell);
637                 updateLocal(bv);
638         }
639 }
640
641
642 void InsetTabular::edit(BufferView * bv, int index)
643 {
644         lyxerr << "InsetTabular::edit" << endl;
645         if (!bv->lockInset(this)) {
646                 lyxerr << "InsetTabular::Cannot lock inset (2)" << endl;
647                 return;
648         }
649
650         locked = true;
651         the_locking_inset = 0;
652         inset_x = 0;
653         inset_y = 0;
654         actcell = index;
655         clearSelection();
656         resetPos(bv);
657         bv->fitCursor();
658
659         UpdatableInset & inset = tabular.getCellInset(actcell);
660         inset.dispatch(FuncRequest(bv, LFUN_INSET_EDIT, "left"));
661         if (the_locking_inset)
662                 updateLocal(bv);
663 }
664
665
666 DispatchResult
667 InsetTabular::priv_dispatch(FuncRequest const & cmd,
668                             idx_type & idx, pos_type & pos)
669 {
670         // We need to save the value of the_locking_inset as the call to
671         // the_locking_inset->localDispatch might unlock it.
672         old_locking_inset = the_locking_inset;
673         DispatchResult result = UpdatableInset::priv_dispatch(cmd, idx, pos);
674         BufferView * bv = cmd.view();
675
676         if (cmd.action == LFUN_INSET_EDIT) {
677
678                 lyxerr << "InsetTabular::edit: " << this << " args: '"
679                         << cmd.argument << "'  first cell: "
680                         << &tabular.cell_info[0][0].inset << endl;
681
682                 if (!bv->lockInset(this)) {
683                         lyxerr << "InsetTabular::Cannot lock inset" << endl;
684                         return DispatchResult(true, true);
685                 }
686
687                 finishUndo();
688                 locked = true;
689                 the_locking_inset = 0;
690                 inset_x = 0;
691                 inset_y = 0;
692
693                 if (cmd.argument.size()) {
694                         if (cmd.argument == "left") {
695                                 if (isRightToLeft(bv))
696                                         actcell = tabular.getLastCellInRow(0);
697                                 else
698                                         actcell = 0;
699                         } else {
700                                 if (isRightToLeft(bv))
701                                         actcell = tabular.getFirstCellInRow(tabular.rows()-1);
702                                 else
703                                         actcell = tabular.getNumberOfCells() - 1;
704                         }
705                         clearSelection();
706                         resetPos(bv);
707                         bv->fitCursor();
708                 }
709
710                 else {
711                         setPos(bv, cmd.x, cmd.y);
712                         clearSelection();
713                         finishUndo();
714                         if (insetHit(bv, cmd.x, cmd.y) && cmd.button() != mouse_button::button3) {
715                                 inset_x = cursorx_ - top_x + tabular.getBeginningOfTextInCell(actcell);
716                                 inset_y = cursory_;
717                                 activateCellInset(bv, cmd.x - inset_x, cmd.y - inset_y, cmd.button());
718                         }
719                 }
720                 return DispatchResult(true, true);
721         }
722
723         if (result.dispatched()) {
724                 resetPos(bv);
725                 return result;
726         }
727
728         if (cmd.action < 0 && cmd.argument.empty())
729                 return DispatchResult(false, FINISHED);
730
731         bool hs = hasSelection();
732
733         result = DispatchResult(true, true);
734         // this one have priority over the locked InsetText, if we're not already
735         // inside another tabular then that one get's priority!
736         if (getFirstLockingInsetOfType(InsetOld::TABULAR_CODE) == this) {
737                 switch (cmd.action) {
738                 case LFUN_MOUSE_PRESS:
739                         lfunMousePress(cmd);
740                         return DispatchResult(true, true);
741
742                 case LFUN_MOUSE_MOTION:
743                         lfunMouseMotion(cmd);
744                         return DispatchResult(true, true);
745
746                 case LFUN_MOUSE_RELEASE:
747                         return DispatchResult(lfunMouseRelease(cmd));
748
749                 case LFUN_CELL_BACKWARD:
750                 case LFUN_CELL_FORWARD:
751                         unlockInsetInInset(bv, the_locking_inset);
752                         if (cmd.action == LFUN_CELL_FORWARD)
753                                 moveNextCell(bv, old_locking_inset != 0);
754                         else
755                                 movePrevCell(bv, old_locking_inset != 0);
756                         clearSelection();
757                         if (hs)
758                                 updateLocal(bv);
759                         if (!the_locking_inset)
760                                 return DispatchResult(true);
761                         return result;
762                 // this to avoid compiler warnings.
763                 default:
764                         break;
765                 }
766         }
767
768         kb_action action = cmd.action;
769         string    arg    = cmd.argument;
770         if (the_locking_inset) {
771                 result = the_locking_inset->dispatch(cmd);
772                 if (result.dispatched()) {
773                         if (result.update()) {
774                                 updateLocal(bv);
775                         } else {
776                                 int const sc = scroll();
777                                 resetPos(bv);
778                                 if (sc != scroll()) {
779                                         // inset has been scrolled
780                                         updateLocal(bv);
781                                 }
782                         }
783                         return result;
784                 } else if (result.val() == FINISHED_UP) {
785                         action = LFUN_UP;
786                         // Make sure to reset status message after
787                         // exiting, e.g. math inset
788                         bv->owner()->clearMessage();
789                 } else if (result.val() == FINISHED_DOWN) {
790                         action = LFUN_DOWN;
791                         bv->owner()->clearMessage();
792                 } else if (result.val() == FINISHED_RIGHT) {
793                         action = LFUN_RIGHT;
794                         bv->owner()->clearMessage();
795                 } else if (result.val() == FINISHED) {
796                         bv->owner()->clearMessage();
797                 }
798         }
799
800         result = DispatchResult(true, true);
801         switch (action) {
802                 // --- Cursor Movements ----------------------------------
803         case LFUN_RIGHTSEL: {
804                 int const start = hasSelection() ? sel_cell_start : actcell;
805                 if (tabular.isLastCellInRow(actcell)) {
806                         setSelection(start, actcell);
807                         break;
808                 }
809
810                 int end = actcell;
811                 // if we are starting a selection, only select
812                 // the current cell at the beginning
813                 if (hasSelection()) {
814                         moveRight(bv, false);
815                         end = actcell;
816                 }
817                 setSelection(start, end);
818                 updateLocal(bv);
819                 break;
820         }
821         case LFUN_RIGHT:
822                 result = moveRight(bv);
823                 clearSelection();
824                 if (hs)
825                         updateLocal(bv);
826                 break;
827         case LFUN_LEFTSEL: {
828                 int const start = hasSelection() ? sel_cell_start : actcell;
829                 if (tabular.isFirstCellInRow(actcell)) {
830                         setSelection(start, actcell);
831                         break;
832                 }
833
834                 int end = actcell;
835                 // if we are starting a selection, only select
836                 // the current cell at the beginning
837                 if (hasSelection()) {
838                         moveLeft(bv, false);
839                         end = actcell;
840                 }
841                 setSelection(start, end);
842                 updateLocal(bv);
843                 break;
844         }
845         case LFUN_LEFT:
846                 result = moveLeft(bv);
847                 clearSelection();
848                 if (hs)
849                         updateLocal(bv);
850                 break;
851         case LFUN_DOWNSEL: {
852                 int const start = hasSelection() ? sel_cell_start : actcell;
853                 int const ocell = actcell;
854                 // if we are starting a selection, only select
855                 // the current cell at the beginning
856                 if (hasSelection()) {
857                         moveDown(bv, false);
858                         if (ocell == sel_cell_end ||
859                             tabular.column_of_cell(ocell) > tabular.column_of_cell(actcell))
860                                 setSelection(start, tabular.getCellBelow(sel_cell_end));
861                         else
862                                 setSelection(start, tabular.getLastCellBelow(sel_cell_end));
863                 } else {
864                         setSelection(start, start);
865                 }
866                 updateLocal(bv);
867         }
868         break;
869         case LFUN_DOWN:
870                 result = moveDown(bv, old_locking_inset != 0);
871                 clearSelection();
872                 if (hs)
873                         updateLocal(bv);
874                 break;
875         case LFUN_UPSEL: {
876                 int const start = hasSelection() ? sel_cell_start : actcell;
877                 int const ocell = actcell;
878                 // if we are starting a selection, only select
879                 // the current cell at the beginning
880                 if (hasSelection()) {
881                         moveUp(bv, false);
882                         if ((ocell == sel_cell_end) ||
883                             (tabular.column_of_cell(ocell)>tabular.column_of_cell(actcell)))
884                                 setSelection(start, tabular.getCellAbove(sel_cell_end));
885                         else
886                                 setSelection(start, tabular.getLastCellAbove(sel_cell_end));
887                 } else {
888                         setSelection(start, start);
889                 }
890                 updateLocal(bv);
891         }
892         break;
893         case LFUN_UP:
894                 result = moveUp(bv, old_locking_inset != 0);
895                 clearSelection();
896                 if (hs)
897                         updateLocal(bv);
898                 break;
899         case LFUN_NEXT: {
900                 if (hs)
901                         clearSelection();
902                 int column = actcol;
903                 unlockInsetInInset(bv, the_locking_inset);
904                 if (bv->top_y() + bv->painter().paperHeight() <
905                     top_baseline + tabular.getHeightOfTabular())
906                         {
907                                 bv->scrollDocView(bv->top_y() + bv->painter().paperHeight());
908                                 actcell = tabular.getCellBelow(first_visible_cell) + column;
909                         } else {
910                                 actcell = tabular.getFirstCellInRow(tabular.rows() - 1) + column;
911                         }
912                 resetPos(bv);
913                 updateLocal(bv);
914                 break;
915         }
916         case LFUN_PRIOR: {
917                 if (hs)
918                         clearSelection();
919                 int column = actcol;
920                 unlockInsetInInset(bv, the_locking_inset);
921                 if (top_baseline < 0) {
922                         bv->scrollDocView(bv->top_y() - bv->painter().paperHeight());
923                         if (top_baseline > 0)
924                                 actcell = column;
925                         else
926                                 actcell = tabular.getCellBelow(first_visible_cell) + column;
927                 } else {
928                         actcell = column;
929                 }
930                 resetPos(bv);
931                 updateLocal(bv);
932                 break;
933         }
934         // none of these make sense for insettabular,
935         // but we must catch them to prevent any
936         // selection from being confused
937         case LFUN_PRIORSEL:
938         case LFUN_NEXTSEL:
939         case LFUN_WORDLEFT:
940         case LFUN_WORDLEFTSEL:
941         case LFUN_WORDRIGHT:
942         case LFUN_WORDRIGHTSEL:
943         case LFUN_WORDSEL:
944         case LFUN_DOWN_PARAGRAPH:
945         case LFUN_DOWN_PARAGRAPHSEL:
946         case LFUN_UP_PARAGRAPH:
947         case LFUN_UP_PARAGRAPHSEL:
948         case LFUN_BACKSPACE:
949         case LFUN_HOME:
950         case LFUN_HOMESEL:
951         case LFUN_END:
952         case LFUN_ENDSEL:
953         case LFUN_BEGINNINGBUF:
954         case LFUN_BEGINNINGBUFSEL:
955         case LFUN_ENDBUF:
956         case LFUN_ENDBUFSEL:
957                 break;
958         case LFUN_LAYOUT_TABULAR:
959                 InsetTabularMailer(*this).showDialog(bv);
960                 break;
961         case LFUN_INSET_DIALOG_UPDATE:
962                 InsetTabularMailer(*this).updateDialog(bv);
963                 break;
964         case LFUN_TABULAR_FEATURE:
965                 if (!tabularFeatures(bv, arg))
966                         result = DispatchResult(false);
967                 break;
968                 // insert file functions
969         case LFUN_FILE_INSERT_ASCII_PARA:
970         case LFUN_FILE_INSERT_ASCII:
971         {
972                 string tmpstr = getContentsOfAsciiFile(bv, arg, false);
973                 if (tmpstr.empty())
974                         break;
975                 if (insertAsciiString(bv, tmpstr, false))
976                         updateLocal(bv);
977                 else
978                         result = DispatchResult(false);
979                 break;
980         }
981         // cut and paste functions
982         case LFUN_CUT:
983                 if (!copySelection(bv))
984                         break;
985                 // no break here!
986         case LFUN_DELETE:
987                 recordUndo(bv, Undo::DELETE);
988                 cutSelection(bv->buffer()->params());
989                 updateLocal(bv);
990                 break;
991         case LFUN_COPY:
992                 if (!hasSelection())
993                         break;
994                 finishUndo();
995                 copySelection(bv);
996                 break;
997         case LFUN_PASTESELECTION:
998         {
999                 string const clip = bv->getClipboard();
1000                 if (clip.empty())
1001                         break;
1002 #if 0
1003                 if (clip.find('\t') != string::npos) {
1004                         int cols = 1;
1005                         int rows = 1;
1006                         int maxCols = 1;
1007                         string::size_type len = clip.length();
1008                         string::size_type p = 0;
1009
1010                         while (p < len &&
1011                               ((p = clip.find_first_of("\t\n", p)) != string::npos)) {
1012                                 switch (clip[p]) {
1013                                 case '\t':
1014                                         ++cols;
1015                                         break;
1016                                 case '\n':
1017                                         if ((p+1) < len)
1018                                                 ++rows;
1019                                         maxCols = max(cols, maxCols);
1020                                         cols = 1;
1021                                         break;
1022                                 }
1023                                 ++p;
1024                         }
1025                         maxCols = max(cols, maxCols);
1026
1027                         paste_tabular.reset(
1028                                 new LyXTabular(bv->buffer()->params(),
1029                                                this, rows, maxCols)
1030                                 );
1031
1032                         string::size_type op = 0;
1033                         int cell = 0;
1034                         int cells = paste_tabular->getNumberOfCells();
1035                         p = cols = 0;
1036                         while ((cell < cells) && (p < len) &&
1037                               (p = clip.find_first_of("\t\n", p)) != string::npos) {
1038                                 if (p >= len)
1039                                         break;
1040                                 switch (clip[p]) {
1041                                 case '\t':
1042                                         paste_tabular->getCellInset(cell)->setText(clip.substr(op, p-op));
1043                                         ++cols;
1044                                         ++cell;
1045                                         break;
1046                                 case '\n':
1047                                         paste_tabular->getCellInset(cell)->setText(clip.substr(op, p-op));
1048                                         while (cols++ < maxCols)
1049                                                 ++cell;
1050                                         cols = 0;
1051                                         break;
1052                                 }
1053                                 ++p;
1054                                 op = p;
1055                         }
1056                         // check for the last cell if there is no trailing '\n'
1057                         if ((cell < cells) && (op < len))
1058                                 paste_tabular->getCellInset(cell)->setText(clip.substr(op, len-op));
1059                 } else
1060 #else
1061                 if (!insertAsciiString(bv, clip, true))
1062 #endif
1063                 {
1064                         // so that the clipboard is used and it goes on
1065                         // to default
1066                         // and executes LFUN_PASTESELECTION in insettext!
1067                         paste_tabular.reset();
1068                 }
1069         }
1070         case LFUN_PASTE:
1071                 if (hasPasteBuffer()) {
1072                         recordUndo(bv, Undo::INSERT);
1073                         pasteSelection(bv);
1074                         updateLocal(bv);
1075                         break;
1076                 }
1077                 // ATTENTION: the function above has to be PASTE and PASTESELECTION!!!
1078         default:
1079                 // handle font changing stuff on selection before we lock the inset
1080                 // in the default part!
1081                 result = DispatchResult(false);
1082                 if (hs) {
1083                         switch(action) {
1084                         case LFUN_LANGUAGE:
1085                         case LFUN_EMPH:
1086                         case LFUN_BOLD:
1087                         case LFUN_NOUN:
1088                         case LFUN_CODE:
1089                         case LFUN_SANS:
1090                         case LFUN_ROMAN:
1091                         case LFUN_DEFAULT:
1092                         case LFUN_UNDERLINE:
1093                         case LFUN_FONT_SIZE:
1094                                 if (bv->dispatch(FuncRequest(bv, action, arg)))
1095                                         result = DispatchResult(true, true);
1096                                 break;
1097                         default:
1098                                 break;
1099                         }
1100                 }
1101                 // we try to activate the actual inset and put this event down to
1102                 // the insets dispatch function.
1103                 if (result.dispatched() || the_locking_inset)
1104                         break;
1105                 if (activateCellInset(bv)) {
1106                         result = the_locking_inset->dispatch(FuncRequest(bv, action, arg));
1107                         if (!result.dispatched()) {
1108                                 unlockInsetInInset(bv, the_locking_inset);
1109                                 // we need to update if this was requested before
1110                                 updateLocal(bv);
1111                                 return DispatchResult(false);
1112                         }
1113                         if (hs)
1114                                 clearSelection();
1115                         updateLocal(bv);
1116                         return result;
1117                 }
1118                 break;
1119         }
1120
1121         if (result.val() >= FINISHED)
1122                 bv->unlockInset(this);
1123         else if (!the_locking_inset && bv->fitCursor())
1124                 updateLocal(bv);
1125
1126         return result;
1127 }
1128
1129
1130 int InsetTabular::latex(Buffer const & buf, ostream & os,
1131                         LatexRunParams const & runparams) const
1132 {
1133         return tabular.latex(buf, os, runparams);
1134 }
1135
1136
1137 int InsetTabular::ascii(Buffer const & buf, ostream & os,
1138                         LatexRunParams const & runparams) const
1139 {
1140         if (runparams.linelen > 0)
1141                 return tabular.ascii(buf, os, runparams,
1142                                      ownerPar(buf, this).params().depth(),
1143                                      false, 0);
1144         return tabular.ascii(buf, os, runparams, 0, false, 0);
1145 }
1146
1147
1148 int InsetTabular::linuxdoc(Buffer const & buf, ostream & os,
1149                            LatexRunParams const & runparams) const
1150 {
1151         return tabular.linuxdoc(buf,os, runparams);
1152 }
1153
1154
1155 int InsetTabular::docbook(Buffer const & buf, ostream & os,
1156                           LatexRunParams const & runparams) const
1157 {
1158         int ret = 0;
1159         InsetOld * master;
1160
1161         // if the table is inside a float it doesn't need the informaltable
1162         // wrapper. Search for it.
1163         for (master = owner();
1164              master && master->lyxCode() != InsetOld::FLOAT_CODE;
1165              master = master->owner());
1166
1167         if (!master) {
1168                 os << "<informaltable>";
1169                 if (runparams.mixed_content)
1170                         os << endl;
1171                 ++ret;
1172         }
1173         ret += tabular.docbook(buf, os, runparams);
1174         if (!master) {
1175                 os << "</informaltable>";
1176                 if (runparams.mixed_content)
1177                         os << endl;
1178                 ++ret;
1179         }
1180         return ret;
1181 }
1182
1183
1184 void InsetTabular::validate(LaTeXFeatures & features) const
1185 {
1186         tabular.validate(features);
1187 }
1188
1189
1190 void InsetTabular::calculate_dimensions_of_cells(MetricsInfo & mi) const
1191 {
1192 #if 1
1193         // if we have a locking_inset we should have to check only this cell for
1194         // change so I'll try this to have a boost, but who knows ;) (Jug?)
1195         // This is _really_ important (André)
1196         if (the_locking_inset == &tabular.getCellInset(actcell)) {
1197                 int maxAsc = 0;
1198                 int maxDesc = 0;
1199                 for (int j = 0; j < tabular.columns(); ++j) {
1200                         Dimension dim;
1201                         MetricsInfo m = mi;
1202                         m.base.textwidth =
1203                                 tabular.column_info[j].p_width.inPixels(mi.base.textwidth);
1204                         tabular.getCellInset(actrow, j).metrics(m, dim);
1205                         maxAsc  = max(dim.asc, maxAsc);
1206                         maxDesc = max(dim.des, maxDesc);
1207                 }
1208                 tabular.setWidthOfCell(actcell, the_locking_inset->width());
1209                 tabular.setAscentOfRow(actrow, maxAsc + ADD_TO_HEIGHT);
1210                 tabular.setDescentOfRow(actrow, maxDesc + ADD_TO_HEIGHT);
1211                 return;
1212         }
1213 #endif
1214
1215         int cell = -1;
1216         for (int i = 0; i < tabular.rows(); ++i) {
1217                 int maxAsc = 0;
1218                 int maxDesc = 0;
1219                 for (int j = 0; j < tabular.columns(); ++j) {
1220                         if (tabular.isPartOfMultiColumn(i, j))
1221                                 continue;
1222                         ++cell;
1223                         Dimension dim;
1224                         MetricsInfo m = mi;
1225                         m.base.textwidth =
1226                                 tabular.column_info[j].p_width.inPixels(mi.base.textwidth);
1227                         tabular.getCellInset(cell).metrics(m, dim);
1228                         maxAsc  = max(maxAsc, dim.asc);
1229                         maxDesc = max(maxDesc, dim.des);
1230                         tabular.setWidthOfCell(cell, dim.wid);
1231                 }
1232                 tabular.setAscentOfRow(i, maxAsc + ADD_TO_HEIGHT);
1233                 tabular.setDescentOfRow(i, maxDesc + ADD_TO_HEIGHT);
1234         }
1235 }
1236
1237
1238 void InsetTabular::getCursor(BufferView & bv, int & x, int & y) const
1239 {
1240         if (the_locking_inset) {
1241                 the_locking_inset->getCursor(bv, x, y);
1242                 return;
1243         }
1244
1245         x = cursorx_;
1246         y = cursory_ + InsetTabular::y();
1247
1248         // Fun stuff
1249         int desc = tabular.getDescentOfRow(actrow);
1250         y += desc;
1251         int ascdesc = tabular.getAscentOfRow(actrow) + desc;
1252         y -= ascdesc / 2;
1253         y += ADD_TO_HEIGHT * 2;
1254         y += TEXT_TO_INSET_OFFSET;
1255 }
1256
1257
1258 void InsetTabular::getCursorPos(BufferView * bv, int & x, int & y) const
1259 {
1260         if (the_locking_inset) {
1261                 the_locking_inset->getCursorPos(bv, x, y);
1262                 return;
1263         }
1264         x = cursorx_ - top_x;
1265         y = cursory_;
1266 }
1267
1268
1269 void InsetTabular::fitInsetCursor(BufferView * bv) const
1270 {
1271         if (the_locking_inset) {
1272                 the_locking_inset->fitInsetCursor(bv);
1273                 return;
1274         }
1275
1276         LyXFont font;
1277         int const asc = font_metrics::maxAscent(font);
1278         int const desc = font_metrics::maxDescent(font);
1279         resetPos(bv);
1280
1281         bv->fitLockedInsetCursor(cursorx_, cursory_, asc, desc);
1282 }
1283
1284
1285 void InsetTabular::setPos(BufferView * bv, int x, int y) const
1286 {
1287         cursory_ = 0;
1288         actcell = actrow = actcol = 0;
1289         int ly = tabular.getDescentOfRow(actrow);
1290
1291         // first search the right row
1292         while (ly < y && actrow + 1 < tabular.rows()) {
1293                 cursory_ += tabular.getDescentOfRow(actrow) +
1294                                  tabular.getAscentOfRow(actrow + 1) +
1295                                  tabular.getAdditionalHeight(actrow + 1);
1296                 ++actrow;
1297                 ly = cursory_ + tabular.getDescentOfRow(actrow);
1298         }
1299         actcell = tabular.getCellNumber(actrow, actcol);
1300
1301         // now search the right column
1302         int lx = tabular.getWidthOfColumn(actcell) -
1303                 tabular.getAdditionalWidth(actcell);
1304
1305         for (; !tabular.isLastCellInRow(actcell) && lx < x; ++actcell)
1306                 lx += tabular.getWidthOfColumn(actcell + 1)
1307                         + tabular.getAdditionalWidth(actcell);
1308
1309         cursorx_ = lx - tabular.getWidthOfColumn(actcell) + top_x + 2;
1310         resetPos(bv);
1311 }
1312
1313
1314 int InsetTabular::getCellXPos(int cell) const
1315 {
1316         int c = cell;
1317
1318         for (; !tabular.isFirstCellInRow(c); --c)
1319                 ;
1320         int lx = tabular.getWidthOfColumn(cell);
1321         for (; c < cell; ++c)
1322                 lx += tabular.getWidthOfColumn(c);
1323
1324         return (lx - tabular.getWidthOfColumn(cell) + top_x);
1325 }
1326
1327
1328 void InsetTabular::resetPos(BufferView * bv) const
1329 {
1330 #ifdef WITH_WARNINGS
1331 #warning This should be fixed in the right manner (20011128 Jug)
1332 #endif
1333         // fast hack to fix infinite repaintings!
1334         if (in_reset_pos > 0)
1335                 return;
1336
1337         int cell = 0;
1338         actcol = tabular.column_of_cell(actcell);
1339         actrow = 0;
1340         cursory_ = 0;
1341         for (; cell < actcell && !tabular.isLastRow(cell); ++cell) {
1342                 if (tabular.isLastCellInRow(cell)) {
1343                         cursory_ += tabular.getDescentOfRow(actrow) +
1344                                          tabular.getAscentOfRow(actrow + 1) +
1345                                          tabular.getAdditionalHeight(actrow + 1);
1346                         ++actrow;
1347                 }
1348         }
1349         if (!locked) {
1350                 if (the_locking_inset)
1351                         inset_y = cursory_;
1352                 return;
1353         }
1354         // we need this only from here on!!!
1355         ++in_reset_pos;
1356         int const offset = ADD_TO_TABULAR_WIDTH + 2;
1357         int new_x = getCellXPos(actcell);
1358         int old_x = cursorx_;
1359         new_x += offset;
1360         cursorx_ = new_x;
1361 //    cursor.x(getCellXPos(actcell) + offset);
1362         if (actcol < tabular.columns() - 1 && scroll(false) &&
1363                 tabular.getWidthOfTabular() < bv->workWidth()-20)
1364         {
1365                 scroll(bv, 0.0F);
1366                 updateLocal(bv);
1367         } else if (the_locking_inset &&
1368                  tabular.getWidthOfColumn(actcell) > bv->workWidth() - 20)
1369         {
1370                 int xx = cursorx_ - offset + bv->text->getRealCursorX();
1371                 if (xx > bv->workWidth()-20) {
1372                         scroll(bv, -(xx - bv->workWidth() + 60));
1373                         updateLocal(bv);
1374                 } else if (xx < 20) {
1375                         if (xx < 0)
1376                                 xx = -xx + 60;
1377                         else
1378                                 xx = 60;
1379                         scroll(bv, xx);
1380                         updateLocal(bv);
1381                 }
1382         } else if (cursorx_ - offset > 20 &&
1383                    cursorx_ - offset + tabular.getWidthOfColumn(actcell)
1384                    > bv->workWidth() - 20) {
1385                 scroll(bv, -tabular.getWidthOfColumn(actcell) - 20);
1386                 updateLocal(bv);
1387         } else if (cursorx_ - offset < 20) {
1388                 scroll(bv, 20 - cursorx_ + offset);
1389                 updateLocal(bv);
1390         } else if (scroll() && top_x > 20 &&
1391                    (top_x + tabular.getWidthOfTabular()) > bv->workWidth() - 20) {
1392                 scroll(bv, old_x - cursorx_);
1393                 updateLocal(bv);
1394         }
1395         if (the_locking_inset) {
1396                 inset_x = cursorx_ - top_x + tabular.getBeginningOfTextInCell(actcell);
1397                 inset_y = cursory_;
1398         }
1399         if ((!the_locking_inset ||
1400              !the_locking_inset->getFirstLockingInsetOfType(TABULAR_CODE)) &&
1401             actcell != oldcell) {
1402                 InsetTabularMailer(*this).updateDialog(bv);
1403                 oldcell = actcell;
1404         }
1405         in_reset_pos = 0;
1406 }
1407
1408
1409 DispatchResult InsetTabular::moveRight(BufferView * bv, bool lock)
1410 {
1411         if (lock && !old_locking_inset) {
1412                 if (activateCellInset(bv))
1413                         return DispatchResult(true, true);
1414         } else {
1415                 bool moved = isRightToLeft(bv)
1416                         ? movePrevCell(bv) : moveNextCell(bv);
1417                 if (!moved)
1418                         return DispatchResult(false, FINISHED_RIGHT);
1419                 if (lock && activateCellInset(bv))
1420                         return DispatchResult(true, true);
1421         }
1422         resetPos(bv);
1423         return DispatchResult(true);
1424 }
1425
1426
1427 DispatchResult InsetTabular::moveLeft(BufferView * bv, bool lock)
1428 {
1429         bool moved = isRightToLeft(bv) ? moveNextCell(bv) : movePrevCell(bv);
1430         if (!moved)
1431                 return DispatchResult(false, FINISHED);
1432         // behind the inset
1433         if (lock && activateCellInset(bv, 0, 0, mouse_button::none, true))
1434                 return DispatchResult(true, true);
1435         resetPos(bv);
1436         return DispatchResult(true);
1437 }
1438
1439
1440 DispatchResult InsetTabular::moveUp(BufferView * bv, bool lock)
1441 {
1442         int const ocell = actcell;
1443         actcell = tabular.getCellAbove(actcell);
1444         if (actcell == ocell) // we moved out of the inset
1445                 return DispatchResult(false, FINISHED_UP);
1446         resetPos(bv);
1447         if (lock) {
1448                 int x = 0;
1449                 int y = 0;
1450                 if (old_locking_inset) {
1451                         old_locking_inset->getCursorPos(bv, x, y);
1452                         x -= cursorx_ + tabular.getBeginningOfTextInCell(actcell);
1453                 }
1454                 if (activateCellInset(bv, x, 0))
1455                         return DispatchResult(true, true);
1456         }
1457         return DispatchResult(true);
1458 }
1459
1460
1461 DispatchResult InsetTabular::moveDown(BufferView * bv, bool lock)
1462 {
1463         int const ocell = actcell;
1464         actcell = tabular.getCellBelow(actcell);
1465         if (actcell == ocell) // we moved out of the inset
1466                 return DispatchResult(false, FINISHED_DOWN);
1467         resetPos(bv);
1468         if (lock) {
1469                 int x = 0;
1470                 int y = 0;
1471                 if (old_locking_inset) {
1472                         old_locking_inset->getCursorPos(bv, x, y);
1473                         x -= cursorx_ + tabular.getBeginningOfTextInCell(actcell);
1474                 }
1475                 if (activateCellInset(bv, x, 0))
1476                         return DispatchResult(true, true);
1477         }
1478         return DispatchResult(true);
1479 }
1480
1481
1482 bool InsetTabular::moveNextCell(BufferView * bv, bool lock)
1483 {
1484         if (isRightToLeft(bv)) {
1485                 if (tabular.isFirstCellInRow(actcell)) {
1486                         int row = tabular.row_of_cell(actcell);
1487                         if (row == tabular.rows() - 1)
1488                                 return false;
1489                         actcell = tabular.getLastCellInRow(row);
1490                         actcell = tabular.getCellBelow(actcell);
1491                 } else {
1492                         if (!actcell)
1493                                 return false;
1494                         --actcell;
1495                 }
1496         } else {
1497                 if (tabular.isLastCell(actcell))
1498                         return false;
1499                 ++actcell;
1500         }
1501         if (lock) {
1502                 bool rtl = tabular.getCellInset(actcell).paragraphs.begin()->
1503                         isRightToLeftPar(bv->buffer()->params());
1504                 activateCellInset(bv, 0, 0, mouse_button::none, !rtl);
1505         }
1506         resetPos(bv);
1507         return true;
1508 }
1509
1510
1511 bool InsetTabular::movePrevCell(BufferView * bv, bool lock)
1512 {
1513         if (isRightToLeft(bv)) {
1514                 if (tabular.isLastCellInRow(actcell)) {
1515                         int row = tabular.row_of_cell(actcell);
1516                         if (row == 0)
1517                                 return false;
1518                         actcell = tabular.getFirstCellInRow(row);
1519                         actcell = tabular.getCellAbove(actcell);
1520                 } else {
1521                         if (tabular.isLastCell(actcell))
1522                                 return false;
1523                         ++actcell;
1524                 }
1525         } else {
1526                 if (!actcell) // first cell
1527                         return false;
1528                 --actcell;
1529         }
1530         if (lock) {
1531                 bool rtl = tabular.getCellInset(actcell).paragraphs.begin()->
1532                         isRightToLeftPar(bv->buffer()->params());
1533                 activateCellInset(bv, 0, 0, mouse_button::none, !rtl);
1534         }
1535         resetPos(bv);
1536         return true;
1537 }
1538
1539
1540 void InsetTabular::setFont(BufferView * bv, LyXFont const & font, bool tall,
1541                            bool selectall)
1542 {
1543         if (selectall) {
1544                 setSelection(0, tabular.getNumberOfCells() - 1);
1545         }
1546         if (hasSelection()) {
1547                 recordUndo(bv, Undo::ATOMIC);
1548                 bool const frozen = undo_frozen;
1549                 if (!frozen)
1550                         freezeUndo();
1551                 // apply the fontchange on the whole selection
1552                 int sel_row_start;
1553                 int sel_row_end;
1554                 int sel_col_start;
1555                 int sel_col_end;
1556                 getSelection(sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1557                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1558                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1559                                 tabular.getCellInset(i, j).setFont(bv, font, tall, true);
1560
1561                 if (!frozen)
1562                         unFreezeUndo();
1563                 if (selectall)
1564                         clearSelection();
1565                 updateLocal(bv);
1566         }
1567         if (the_locking_inset)
1568                 the_locking_inset->setFont(bv, font, tall);
1569 }
1570
1571
1572 bool InsetTabular::tabularFeatures(BufferView * bv, string const & what)
1573 {
1574         LyXTabular::Feature action = LyXTabular::LAST_ACTION;
1575
1576         int i = 0;
1577         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
1578                 string const tmp = tabularFeature[i].feature;
1579
1580                 if (tmp == what.substr(0, tmp.length())) {
1581                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
1582                         //tabularFeatures[i].feature.length())) {
1583                         action = tabularFeature[i].action;
1584                         break;
1585                 }
1586         }
1587         if (action == LyXTabular::LAST_ACTION)
1588                 return false;
1589
1590         string const val =
1591                 ltrim(what.substr(tabularFeature[i].feature.length()));
1592         tabularFeatures(bv, action, val);
1593         return true;
1594 }
1595
1596 namespace {
1597
1598 void checkLongtableSpecial(LyXTabular::ltType & ltt,
1599                           string const & special, bool & flag)
1600 {
1601         if (special == "dl_above") {
1602                 ltt.topDL = flag;
1603                 ltt.set = false;
1604         } else if (special == "dl_below") {
1605                 ltt.bottomDL = flag;
1606                 ltt.set = false;
1607         } else if (special == "empty") {
1608                 ltt.empty = flag;
1609                 ltt.set = false;
1610         } else if (flag) {
1611                 ltt.empty = false;
1612                 ltt.set = true;
1613         }
1614 }
1615
1616 } // anon namespace
1617
1618
1619 void InsetTabular::tabularFeatures(BufferView * bv,
1620         LyXTabular::Feature feature, string const & value)
1621 {
1622         int sel_col_start;
1623         int sel_col_end;
1624         int sel_row_start;
1625         int sel_row_end;
1626         bool setLines = false;
1627         LyXAlignment setAlign = LYX_ALIGN_LEFT;
1628         LyXTabular::VAlignment setVAlign = LyXTabular::LYX_VALIGN_TOP;
1629
1630         switch (feature) {
1631
1632         case LyXTabular::M_ALIGN_LEFT:
1633         case LyXTabular::ALIGN_LEFT:
1634                 setAlign = LYX_ALIGN_LEFT;
1635                 break;
1636
1637         case LyXTabular::M_ALIGN_RIGHT:
1638         case LyXTabular::ALIGN_RIGHT:
1639                 setAlign = LYX_ALIGN_RIGHT;
1640                 break;
1641
1642         case LyXTabular::M_ALIGN_CENTER:
1643         case LyXTabular::ALIGN_CENTER:
1644                 setAlign = LYX_ALIGN_CENTER;
1645                 break;
1646
1647         case LyXTabular::ALIGN_BLOCK:
1648                 setAlign = LYX_ALIGN_BLOCK;
1649                 break;
1650
1651         case LyXTabular::M_VALIGN_TOP:
1652         case LyXTabular::VALIGN_TOP:
1653                 setVAlign = LyXTabular::LYX_VALIGN_TOP;
1654                 break;
1655
1656         case LyXTabular::M_VALIGN_BOTTOM:
1657         case LyXTabular::VALIGN_BOTTOM:
1658                 setVAlign = LyXTabular::LYX_VALIGN_BOTTOM;
1659                 break;
1660
1661         case LyXTabular::M_VALIGN_MIDDLE:
1662         case LyXTabular::VALIGN_MIDDLE:
1663                 setVAlign = LyXTabular::LYX_VALIGN_MIDDLE;
1664                 break;
1665
1666         default:
1667                 break;
1668         }
1669
1670         if (hasSelection()) {
1671                 getSelection(sel_row_start, sel_row_end, sel_col_start, sel_col_end);
1672         } else {
1673                 sel_col_start = sel_col_end = tabular.column_of_cell(actcell);
1674                 sel_row_start = sel_row_end = tabular.row_of_cell(actcell);
1675         }
1676         recordUndo(bv, Undo::ATOMIC);
1677
1678         int row =  tabular.row_of_cell(actcell);
1679         int column = tabular.column_of_cell(actcell);
1680         bool flag = true;
1681         LyXTabular::ltType ltt;
1682
1683         switch (feature) {
1684
1685         case LyXTabular::SET_PWIDTH: {
1686                 LyXLength const len(value);
1687                 LyXLength const & oldlen = tabular.getColumnPWidth(actcell);
1688
1689                 tabular.setColumnPWidth(actcell, len);
1690                 if (oldlen != len) {
1691                         // We need this otherwise we won't resize
1692                         // the insettext of the active cell (if any)
1693                         // until later (see InsetText::do_resize)
1694                         unlockInsetInInset(bv, the_locking_inset);
1695                         bv->update();
1696                 }
1697
1698                 if (len.zero()
1699                     && tabular.getAlignment(actcell, true) == LYX_ALIGN_BLOCK)
1700                         tabularFeatures(bv, LyXTabular::ALIGN_CENTER, string());
1701                 else if (!len.zero()
1702                          && tabular.getAlignment(actcell, true) != LYX_ALIGN_BLOCK)
1703                         tabularFeatures(bv, LyXTabular::ALIGN_BLOCK, string());
1704                 break;
1705         }
1706
1707         case LyXTabular::SET_MPWIDTH:
1708         {
1709                 LyXLength const len(value);
1710                 LyXLength const & oldlen = tabular.getPWidth(actcell);
1711                 tabular.setMColumnPWidth(actcell, len);
1712                 if (oldlen != len) {
1713                         // We need this otherwise we won't resize
1714                         // the insettext of the active cell (if any)
1715                         // until later (see InsetText::do_resize)
1716                         unlockInsetInInset(bv, the_locking_inset);
1717                         updateLocal(bv);
1718                 }
1719         }
1720         break;
1721
1722         case LyXTabular::SET_SPECIAL_COLUMN:
1723         case LyXTabular::SET_SPECIAL_MULTI:
1724                 tabular.setAlignSpecial(actcell,value,feature);
1725                 updateLocal(bv);
1726                 break;
1727
1728         case LyXTabular::APPEND_ROW:
1729                 // append the row into the tabular
1730                 unlockInsetInInset(bv, the_locking_inset);
1731                 tabular.appendRow(bv->buffer()->params(), actcell);
1732                 tabular.setOwner(this);
1733                 updateLocal(bv);
1734                 break;
1735
1736         case LyXTabular::APPEND_COLUMN:
1737                 // append the column into the tabular
1738                 unlockInsetInInset(bv, the_locking_inset);
1739                 tabular.appendColumn(bv->buffer()->params(), actcell);
1740                 tabular.setOwner(this);
1741                 actcell = tabular.getCellNumber(row, column);
1742                 updateLocal(bv);
1743                 break;
1744
1745         case LyXTabular::DELETE_ROW:
1746                 unlockInsetInInset(bv, the_locking_inset);
1747                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1748                         tabular.deleteRow(sel_row_start);
1749                 if (sel_row_start >= tabular.rows())
1750                         --sel_row_start;
1751                 actcell = tabular.getCellNumber(sel_row_start, column);
1752                 clearSelection();
1753                 updateLocal(bv);
1754                 break;
1755
1756         case LyXTabular::DELETE_COLUMN:
1757                 unlockInsetInInset(bv, the_locking_inset);
1758                 for (int i = sel_col_start; i <= sel_col_end; ++i)
1759                         tabular.deleteColumn(sel_col_start);
1760                 if (sel_col_start >= tabular.columns())
1761                         --sel_col_start;
1762                 actcell = tabular.getCellNumber(row, sel_col_start);
1763                 clearSelection();
1764                 updateLocal(bv);
1765                 break;
1766
1767         case LyXTabular::M_TOGGLE_LINE_TOP:
1768                 flag = false;
1769         case LyXTabular::TOGGLE_LINE_TOP: {
1770                 bool lineSet = !tabular.topLine(actcell, flag);
1771                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1772                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1773                                 tabular.setTopLine(
1774                                         tabular.getCellNumber(i, j),
1775                                         lineSet, flag);
1776                 updateLocal(bv);
1777                 break;
1778         }
1779
1780         case LyXTabular::M_TOGGLE_LINE_BOTTOM:
1781                 flag = false;
1782         case LyXTabular::TOGGLE_LINE_BOTTOM: {
1783                 bool lineSet = !tabular.bottomLine(actcell, flag);
1784                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1785                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1786                                 tabular.setBottomLine(
1787                                         tabular.getCellNumber(i, j),
1788                                         lineSet,
1789                                         flag);
1790                 updateLocal(bv);
1791                 break;
1792         }
1793
1794         case LyXTabular::M_TOGGLE_LINE_LEFT:
1795                 flag = false;
1796         case LyXTabular::TOGGLE_LINE_LEFT: {
1797                 bool lineSet = !tabular.leftLine(actcell, flag);
1798                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1799                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1800                                 tabular.setLeftLine(
1801                                         tabular.getCellNumber(i,j),
1802                                         lineSet,
1803                                         flag);
1804                 updateLocal(bv);
1805                 break;
1806         }
1807
1808         case LyXTabular::M_TOGGLE_LINE_RIGHT:
1809                 flag = false;
1810         case LyXTabular::TOGGLE_LINE_RIGHT: {
1811                 bool lineSet = !tabular.rightLine(actcell, flag);
1812                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1813                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1814                                 tabular.setRightLine(
1815                                         tabular.getCellNumber(i,j),
1816                                         lineSet,
1817                                         flag);
1818                 updateLocal(bv);
1819                 break;
1820         }
1821
1822         case LyXTabular::M_ALIGN_LEFT:
1823         case LyXTabular::M_ALIGN_RIGHT:
1824         case LyXTabular::M_ALIGN_CENTER:
1825                 flag = false;
1826         case LyXTabular::ALIGN_LEFT:
1827         case LyXTabular::ALIGN_RIGHT:
1828         case LyXTabular::ALIGN_CENTER:
1829         case LyXTabular::ALIGN_BLOCK:
1830                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1831                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1832                                 tabular.setAlignment(
1833                                         tabular.getCellNumber(i, j),
1834                                         setAlign,
1835                                         flag);
1836                 updateLocal(bv);
1837                 break;
1838
1839         case LyXTabular::M_VALIGN_TOP:
1840         case LyXTabular::M_VALIGN_BOTTOM:
1841         case LyXTabular::M_VALIGN_MIDDLE:
1842                 flag = false;
1843         case LyXTabular::VALIGN_TOP:
1844         case LyXTabular::VALIGN_BOTTOM:
1845         case LyXTabular::VALIGN_MIDDLE:
1846                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1847                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1848                                 tabular.setVAlignment(
1849                                         tabular.getCellNumber(i, j),
1850                                         setVAlign, flag);
1851                 updateLocal(bv);
1852                 break;
1853
1854         case LyXTabular::MULTICOLUMN: {
1855                 if (sel_row_start != sel_row_end) {
1856 #ifdef WITH_WARNINGS
1857 #warning Need I say it ? This is horrible.
1858 #endif
1859                         Alert::error(_("Error setting multicolumn"),
1860                                    _("You cannot set multicolumn vertically."));
1861                         return;
1862                 }
1863                 // just multicol for one Single Cell
1864                 if (!hasSelection()) {
1865                         // check wether we are completly in a multicol
1866                         if (tabular.isMultiColumn(actcell))
1867                                 tabular.unsetMultiColumn(actcell);
1868                         else
1869                                 tabular.setMultiColumn(bv->buffer(), actcell, 1);
1870                         updateLocal(bv);
1871                         break;
1872                 }
1873                 // we have a selection so this means we just add all this
1874                 // cells to form a multicolumn cell
1875                 int s_start;
1876                 int s_end;
1877
1878                 if (sel_cell_start > sel_cell_end) {
1879                         s_start = sel_cell_end;
1880                         s_end = sel_cell_start;
1881                 } else {
1882                         s_start = sel_cell_start;
1883                         s_end = sel_cell_end;
1884                 }
1885                 tabular.setMultiColumn(bv->buffer(), s_start, s_end - s_start + 1);
1886                 actcell = s_start;
1887                 clearSelection();
1888                 updateLocal(bv);
1889                 break;
1890         }
1891
1892         case LyXTabular::SET_ALL_LINES:
1893                 setLines = true;
1894         case LyXTabular::UNSET_ALL_LINES:
1895                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1896                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1897                                 tabular.setAllLines(
1898                                         tabular.getCellNumber(i,j), setLines);
1899                 updateLocal(bv);
1900                 break;
1901
1902         case LyXTabular::SET_LONGTABULAR:
1903                 tabular.setLongTabular(true);
1904                 updateLocal(bv); // because this toggles displayed
1905                 break;
1906
1907         case LyXTabular::UNSET_LONGTABULAR:
1908                 tabular.setLongTabular(false);
1909                 updateLocal(bv); // because this toggles displayed
1910                 break;
1911
1912         case LyXTabular::SET_ROTATE_TABULAR:
1913                 tabular.setRotateTabular(true);
1914                 break;
1915
1916         case LyXTabular::UNSET_ROTATE_TABULAR:
1917                 tabular.setRotateTabular(false);
1918                 break;
1919
1920         case LyXTabular::SET_ROTATE_CELL:
1921                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1922                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1923                                 tabular.setRotateCell(
1924                                         tabular.getCellNumber(i, j), true);
1925                 break;
1926
1927         case LyXTabular::UNSET_ROTATE_CELL:
1928                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1929                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1930                                 tabular.setRotateCell(
1931                                         tabular.getCellNumber(i, j), false);
1932                 break;
1933
1934         case LyXTabular::SET_USEBOX: {
1935                 LyXTabular::BoxType val = LyXTabular::BoxType(strToInt(value));
1936                 if (val == tabular.getUsebox(actcell))
1937                         val = LyXTabular::BOX_NONE;
1938                 for (int i = sel_row_start; i <= sel_row_end; ++i)
1939                         for (int j = sel_col_start; j <= sel_col_end; ++j)
1940                                 tabular.setUsebox(tabular.getCellNumber(i, j), val);
1941                 break;
1942         }
1943
1944         case LyXTabular::UNSET_LTFIRSTHEAD:
1945                 flag = false;
1946         case LyXTabular::SET_LTFIRSTHEAD:
1947                 tabular.getRowOfLTFirstHead(row, ltt);
1948                 checkLongtableSpecial(ltt, value, flag);
1949                 tabular.setLTHead(row, flag, ltt, true);
1950                 break;
1951
1952         case LyXTabular::UNSET_LTHEAD:
1953                 flag = false;
1954         case LyXTabular::SET_LTHEAD:
1955                 tabular.getRowOfLTHead(row, ltt);
1956                 checkLongtableSpecial(ltt, value, flag);
1957                 tabular.setLTHead(row, flag, ltt, false);
1958                 break;
1959
1960         case LyXTabular::UNSET_LTFOOT:
1961                 flag = false;
1962         case LyXTabular::SET_LTFOOT:
1963                 tabular.getRowOfLTFoot(row, ltt);
1964                 checkLongtableSpecial(ltt, value, flag);
1965                 tabular.setLTFoot(row, flag, ltt, false);
1966                 break;
1967
1968         case LyXTabular::UNSET_LTLASTFOOT:
1969                 flag = false;
1970         case LyXTabular::SET_LTLASTFOOT:
1971                 tabular.getRowOfLTLastFoot(row, ltt);
1972                 checkLongtableSpecial(ltt, value, flag);
1973                 tabular.setLTFoot(row, flag, ltt, true);
1974                 break;
1975
1976         case LyXTabular::SET_LTNEWPAGE:
1977                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
1978                 break;
1979
1980         // dummy stuff just to avoid warnings
1981         case LyXTabular::LAST_ACTION:
1982                 break;
1983         }
1984
1985         InsetTabularMailer(*this).updateDialog(bv);
1986 }
1987
1988
1989 bool InsetTabular::activateCellInset(BufferView * bv, int x, int y,
1990         mouse_button::state button, bool behind)
1991 {
1992         UpdatableInset & inset = tabular.getCellInset(actcell);
1993         if (behind) {
1994 #warning metrics?
1995                 x = inset.x() + inset.width();
1996                 y = inset.descent();
1997         }
1998         //inset_x = cursorx_ - top_x + tabular.getBeginningOfTextInCell(actcell);
1999         //inset_y = cursory_;
2000         inset.dispatch(FuncRequest(bv, LFUN_INSET_EDIT, x,  y, button));
2001         if (!the_locking_inset)
2002                 return false;
2003         updateLocal(bv);
2004         return the_locking_inset;
2005 }
2006
2007
2008 bool InsetTabular::insetHit(BufferView *, int x, int) const
2009 {
2010         return x + top_x > cursorx_ + tabular.getBeginningOfTextInCell(actcell);
2011 }
2012
2013
2014 void InsetTabular::deleteLyXText(BufferView * /*bv*/, bool /*recursive*/) const
2015 {
2016         //resizeLyXText(bv, recursive);
2017 }
2018
2019
2020 LyXText * InsetTabular::getLyXText(BufferView const * bv,
2021                                    bool const recursive) const
2022 {
2023         if (the_locking_inset)
2024                 return the_locking_inset->getLyXText(bv, recursive);
2025         return InsetOld::getLyXText(bv, recursive);
2026 }
2027
2028
2029 bool InsetTabular::showInsetDialog(BufferView * bv) const
2030 {
2031         if (!the_locking_inset || !the_locking_inset->showInsetDialog(bv))
2032                 InsetTabularMailer(*this).showDialog(bv);
2033         return true;
2034 }
2035
2036
2037 void InsetTabular::openLayoutDialog(BufferView * bv) const
2038 {
2039         if (the_locking_inset) {
2040                 InsetTabular * inset = static_cast<InsetTabular *>
2041                         (the_locking_inset->getFirstLockingInsetOfType(TABULAR_CODE));
2042                 if (inset) {
2043                         inset->openLayoutDialog(bv);
2044                         return;
2045                 }
2046         }
2047         InsetTabularMailer(*this).showDialog(bv);
2048 }
2049
2050
2051 //
2052 // function returns an object as defined in func_status.h:
2053 // states OK, Unknown, Disabled, On, Off.
2054 //
2055 FuncStatus InsetTabular::getStatus(string const & what) const
2056 {
2057         int action = LyXTabular::LAST_ACTION;
2058         FuncStatus status;
2059
2060         int i = 0;
2061         for (; tabularFeature[i].action != LyXTabular::LAST_ACTION; ++i) {
2062                 string const tmp = tabularFeature[i].feature;
2063                 if (tmp == what.substr(0, tmp.length())) {
2064                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
2065                         //   tabularFeatures[i].feature.length())) {
2066                         action = tabularFeature[i].action;
2067                         break;
2068                 }
2069         }
2070         if (action == LyXTabular::LAST_ACTION) {
2071                 status.clear();
2072                 status.unknown(true);
2073                 return status;
2074         }
2075
2076         string const argument
2077                 = ltrim(what.substr(tabularFeature[i].feature.length()));
2078
2079         int sel_row_start;
2080         int sel_row_end;
2081         int dummy;
2082         LyXTabular::ltType dummyltt;
2083         bool flag = true;
2084
2085         if (hasSelection())
2086                 getSelection(sel_row_start, sel_row_end, dummy, dummy);
2087         else
2088                 sel_row_start = sel_row_end = tabular.row_of_cell(actcell);
2089
2090         switch (action) {
2091         case LyXTabular::SET_PWIDTH:
2092         case LyXTabular::SET_MPWIDTH:
2093         case LyXTabular::SET_SPECIAL_COLUMN:
2094         case LyXTabular::SET_SPECIAL_MULTI:
2095         case LyXTabular::APPEND_ROW:
2096         case LyXTabular::APPEND_COLUMN:
2097         case LyXTabular::DELETE_ROW:
2098         case LyXTabular::DELETE_COLUMN:
2099         case LyXTabular::SET_ALL_LINES:
2100         case LyXTabular::UNSET_ALL_LINES:
2101                 status.clear();
2102                 return status;
2103
2104         case LyXTabular::MULTICOLUMN:
2105                 status.setOnOff(tabular.isMultiColumn(actcell));
2106                 break;
2107
2108         case LyXTabular::M_TOGGLE_LINE_TOP:
2109                 flag = false;
2110         case LyXTabular::TOGGLE_LINE_TOP:
2111                 status.setOnOff(tabular.topLine(actcell, flag));
2112                 break;
2113
2114         case LyXTabular::M_TOGGLE_LINE_BOTTOM:
2115                 flag = false;
2116         case LyXTabular::TOGGLE_LINE_BOTTOM:
2117                 status.setOnOff(tabular.bottomLine(actcell, flag));
2118                 break;
2119
2120         case LyXTabular::M_TOGGLE_LINE_LEFT:
2121                 flag = false;
2122         case LyXTabular::TOGGLE_LINE_LEFT:
2123                 status.setOnOff(tabular.leftLine(actcell, flag));
2124                 break;
2125
2126         case LyXTabular::M_TOGGLE_LINE_RIGHT:
2127                 flag = false;
2128         case LyXTabular::TOGGLE_LINE_RIGHT:
2129                 status.setOnOff(tabular.rightLine(actcell, flag));
2130                 break;
2131
2132         case LyXTabular::M_ALIGN_LEFT:
2133                 flag = false;
2134         case LyXTabular::ALIGN_LEFT:
2135                 status.setOnOff(tabular.getAlignment(actcell, flag) == LYX_ALIGN_LEFT);
2136                 break;
2137
2138         case LyXTabular::M_ALIGN_RIGHT:
2139                 flag = false;
2140         case LyXTabular::ALIGN_RIGHT:
2141                 status.setOnOff(tabular.getAlignment(actcell, flag) == LYX_ALIGN_RIGHT);
2142                 break;
2143
2144         case LyXTabular::M_ALIGN_CENTER:
2145                 flag = false;
2146         case LyXTabular::ALIGN_CENTER:
2147                 status.setOnOff(tabular.getAlignment(actcell, flag) == LYX_ALIGN_CENTER);
2148                 break;
2149
2150         case LyXTabular::ALIGN_BLOCK:
2151                 status.disabled(tabular.getPWidth(actcell).zero());
2152                 status.setOnOff(tabular.getAlignment(actcell, flag) == LYX_ALIGN_BLOCK);
2153                 break;
2154
2155         case LyXTabular::M_VALIGN_TOP:
2156                 flag = false;
2157         case LyXTabular::VALIGN_TOP:
2158                 status.setOnOff(tabular.getVAlignment(actcell, flag) == LyXTabular::LYX_VALIGN_TOP);
2159                 break;
2160
2161         case LyXTabular::M_VALIGN_BOTTOM:
2162                 flag = false;
2163         case LyXTabular::VALIGN_BOTTOM:
2164                 status.setOnOff(tabular.getVAlignment(actcell, flag) == LyXTabular::LYX_VALIGN_BOTTOM);
2165                 break;
2166
2167         case LyXTabular::M_VALIGN_MIDDLE:
2168                 flag = false;
2169         case LyXTabular::VALIGN_MIDDLE:
2170                 status.setOnOff(tabular.getVAlignment(actcell, flag) == LyXTabular::LYX_VALIGN_MIDDLE);
2171                 break;
2172
2173         case LyXTabular::SET_LONGTABULAR:
2174                 status.setOnOff(tabular.isLongTabular());
2175                 break;
2176
2177         case LyXTabular::UNSET_LONGTABULAR:
2178                 status.setOnOff(!tabular.isLongTabular());
2179                 break;
2180
2181         case LyXTabular::SET_ROTATE_TABULAR:
2182                 status.setOnOff(tabular.getRotateTabular());
2183                 break;
2184
2185         case LyXTabular::UNSET_ROTATE_TABULAR:
2186                 status.setOnOff(!tabular.getRotateTabular());
2187                 break;
2188
2189         case LyXTabular::SET_ROTATE_CELL:
2190                 status.setOnOff(tabular.getRotateCell(actcell));
2191                 break;
2192
2193         case LyXTabular::UNSET_ROTATE_CELL:
2194                 status.setOnOff(!tabular.getRotateCell(actcell));
2195                 break;
2196
2197         case LyXTabular::SET_USEBOX:
2198                 status.setOnOff(strToInt(argument) == tabular.getUsebox(actcell));
2199                 break;
2200
2201         case LyXTabular::SET_LTFIRSTHEAD:
2202                 status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
2203                 break;
2204
2205         case LyXTabular::SET_LTHEAD:
2206                 status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
2207                 break;
2208
2209         case LyXTabular::SET_LTFOOT:
2210                 status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
2211                 break;
2212
2213         case LyXTabular::SET_LTLASTFOOT:
2214                 status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
2215                 break;
2216
2217         case LyXTabular::SET_LTNEWPAGE:
2218                 status.setOnOff(tabular.getLTNewPage(sel_row_start));
2219                 break;
2220
2221         default:
2222                 status.clear();
2223                 status.disabled(true);
2224                 break;
2225         }
2226         return status;
2227 }
2228
2229
2230 void InsetTabular::getLabelList(Buffer const & buffer,
2231                                 std::vector<string> & list) const
2232 {
2233         tabular.getLabelList(buffer, list);
2234 }
2235
2236
2237 bool InsetTabular::copySelection(BufferView * bv)
2238 {
2239         if (!hasSelection())
2240                 return false;
2241
2242         int sel_col_start = tabular.column_of_cell(sel_cell_start);
2243         int sel_col_end = tabular.column_of_cell(sel_cell_end);
2244         if (sel_col_start > sel_col_end) {
2245                 sel_col_start = sel_col_end;
2246                 sel_col_end = tabular.right_column_of_cell(sel_cell_start);
2247         } else {
2248                 sel_col_end = tabular.right_column_of_cell(sel_cell_end);
2249         }
2250
2251         int sel_row_start = tabular.row_of_cell(sel_cell_start);
2252         int sel_row_end = tabular.row_of_cell(sel_cell_end);
2253         if (sel_row_start > sel_row_end)
2254                 swap(sel_row_start, sel_row_end);
2255
2256         paste_tabular.reset(new LyXTabular(tabular));
2257         paste_tabular->setOwner(this);
2258
2259         for (int i = 0; i < sel_row_start; ++i)
2260                 paste_tabular->deleteRow(0);
2261
2262         int const rows = sel_row_end - sel_row_start + 1;
2263         while (paste_tabular->rows() > rows)
2264                 paste_tabular->deleteRow(rows);
2265
2266         paste_tabular->setTopLine(0, true, true);
2267         paste_tabular->setBottomLine(paste_tabular->getFirstCellInRow(rows - 1),
2268                                      true, true);
2269
2270         for (int i = 0; i < sel_col_start; ++i)
2271                 paste_tabular->deleteColumn(0);
2272
2273         int const columns = sel_col_end - sel_col_start + 1;
2274         while (paste_tabular->columns() > columns)
2275                 paste_tabular->deleteColumn(columns);
2276
2277         paste_tabular->setLeftLine(0, true, true);
2278         paste_tabular->setRightLine(paste_tabular->getLastCellInRow(0),
2279                                     true, true);
2280
2281         ostringstream os;
2282         LatexRunParams const runparams;
2283         paste_tabular->ascii(*bv->buffer(), os, runparams,
2284                              ownerPar(*bv->buffer(), this).params().depth(), true, '\t');
2285         bv->stuffClipboard(os.str());
2286         return true;
2287 }
2288
2289
2290 bool InsetTabular::pasteSelection(BufferView * bv)
2291 {
2292         if (!paste_tabular)
2293                 return false;
2294
2295         for (int r1 = 0, r2 = actrow;
2296              r1 < paste_tabular->rows() && r2 < tabular.rows();
2297              ++r1, ++r2) {
2298                 for (int c1 = 0, c2 = actcol;
2299                     c1 < paste_tabular->columns() && c2 < tabular.columns();
2300                     ++c1, ++c2) {
2301                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
2302                             tabular.isPartOfMultiColumn(r2, c2))
2303                                 continue;
2304                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
2305                                 --c2;
2306                                 continue;
2307                         }
2308                         if (tabular.isPartOfMultiColumn(r2, c2)) {
2309                                 --c1;
2310                                 continue;
2311                         }
2312                         InsetText & inset = tabular.getCellInset(r2, c2);
2313                         inset = paste_tabular->getCellInset(r1, c1);
2314                         inset.setOwner(this);
2315                         inset.deleteLyXText(bv);
2316                         inset.markNew();
2317                 }
2318         }
2319         return true;
2320 }
2321
2322
2323 bool InsetTabular::cutSelection(BufferParams const & bp)
2324 {
2325         if (!hasSelection())
2326                 return false;
2327
2328         int sel_col_start = tabular.column_of_cell(sel_cell_start);
2329         int sel_col_end = tabular.column_of_cell(sel_cell_end);
2330         if (sel_col_start > sel_col_end) {
2331                 sel_col_start = sel_col_end;
2332                 sel_col_end = tabular.right_column_of_cell(sel_cell_start);
2333         } else {
2334                 sel_col_end = tabular.right_column_of_cell(sel_cell_end);
2335         }
2336
2337         int sel_row_start = tabular.row_of_cell(sel_cell_start);
2338         int sel_row_end = tabular.row_of_cell(sel_cell_end);
2339
2340         if (sel_row_start > sel_row_end)
2341                 swap(sel_row_start, sel_row_end);
2342
2343         if (sel_cell_start > sel_cell_end)
2344                 swap(sel_cell_start, sel_cell_end);
2345
2346         for (int i = sel_row_start; i <= sel_row_end; ++i)
2347                 for (int j = sel_col_start; j <= sel_col_end; ++j)
2348                         tabular.getCellInset(tabular.getCellNumber(i, j))
2349                                 .clear(bp.tracking_changes);
2350         return true;
2351 }
2352
2353
2354 bool InsetTabular::isRightToLeft(BufferView * bv)
2355 {
2356         return bv->getParentLanguage(this)->RightToLeft();
2357 }
2358
2359
2360 int InsetTabular::scroll(bool recursive) const
2361 {
2362         int sx = UpdatableInset::scroll(false);
2363
2364         if (recursive && the_locking_inset)
2365                 sx += the_locking_inset->scroll(recursive);
2366
2367         return sx;
2368 }
2369
2370
2371 void InsetTabular::getSelection(int & srow, int & erow,
2372                                 int & scol, int & ecol) const
2373 {
2374         int const start = hasSelection() ? sel_cell_start : actcell;
2375         int const end = hasSelection() ? sel_cell_end : actcell;
2376
2377         srow = tabular.row_of_cell(start);
2378         erow = tabular.row_of_cell(end);
2379         if (srow > erow)
2380                 swap(srow, erow);
2381
2382         scol = tabular.column_of_cell(start);
2383         ecol = tabular.column_of_cell(end);
2384         if (scol > ecol)
2385                 swap(scol, ecol);
2386         else
2387                 ecol = tabular.right_column_of_cell(end);
2388 }
2389
2390
2391 ParagraphList * InsetTabular::getParagraphs(int i) const
2392 {
2393         return i < tabular.getNumberOfCells()
2394                 ? tabular.getCellInset(i).getParagraphs(0)
2395                 : 0;
2396 }
2397
2398
2399 int InsetTabular::numParagraphs() const
2400 {
2401         return tabular.getNumberOfCells();
2402 }
2403
2404
2405 LyXText * InsetTabular::getText(int i) const
2406 {
2407         return i < tabular.getNumberOfCells()
2408                 ?  tabular.getCellInset(i).getText(0)
2409                 : 0;
2410 }
2411
2412
2413 LyXCursor const & InsetTabular::cursor(BufferView * bv) const
2414 {
2415         if (the_locking_inset)
2416                 return the_locking_inset->cursor(bv);
2417         return InsetOld::cursor(bv);
2418 }
2419
2420
2421 void InsetTabular::markErased()
2422 {
2423         for (int cell = 0; cell < tabular.getNumberOfCells(); ++cell)
2424                 tabular.getCellInset(cell).markErased();
2425 }
2426
2427
2428 bool InsetTabular::nextChange(BufferView * bv, lyx::pos_type & length)
2429 {
2430         if (the_locking_inset) {
2431                 if (the_locking_inset->nextChange(bv, length)) {
2432                         updateLocal(bv);
2433                         return true;
2434                 }
2435                 if (tabular.isLastCell(actcell))
2436                         return false;
2437                 ++actcell;
2438         }
2439         InsetText & inset = tabular.getCellInset(actcell);
2440         if (inset.nextChange(bv, length)) {
2441                 updateLocal(bv);
2442                 return true;
2443         }
2444         while (!tabular.isLastCell(actcell)) {
2445                 ++actcell;
2446                 InsetText & inset = tabular.getCellInset(actcell);
2447                 if (inset.nextChange(bv, length)) {
2448                         updateLocal(bv);
2449                         return true;
2450                 }
2451         }
2452         return false;
2453 }
2454
2455
2456 bool InsetTabular::searchForward(BufferView * bv, string const & str,
2457                                  bool cs, bool mw)
2458 {
2459         int cell = 0;
2460         if (the_locking_inset) {
2461                 if (the_locking_inset->searchForward(bv, str, cs, mw)) {
2462                         updateLocal(bv);
2463                         return true;
2464                 }
2465                 if (tabular.isLastCell(actcell))
2466                         return false;
2467                 cell = actcell + 1;
2468         }
2469         InsetText & inset = tabular.getCellInset(cell);
2470         if (inset.searchForward(bv, str, cs, mw)) {
2471                 updateLocal(bv);
2472                 return true;
2473         }
2474         while (!tabular.isLastCell(cell)) {
2475                 ++cell;
2476                 InsetText & inset = tabular.getCellInset(cell);
2477                 if (inset.searchForward(bv, str, cs, mw)) {
2478                         updateLocal(bv);
2479                         return true;
2480                 }
2481         }
2482         return false;
2483 }
2484
2485
2486 bool InsetTabular::searchBackward(BufferView * bv, string const & str,
2487                                bool cs, bool mw)
2488 {
2489         int cell = tabular.getNumberOfCells();
2490         if (the_locking_inset) {
2491                 if (the_locking_inset->searchBackward(bv, str, cs, mw)) {
2492                         updateLocal(bv);
2493                         return true;
2494                 }
2495                 cell = actcell;
2496         }
2497
2498         while (cell) {
2499                 --cell;
2500                 InsetText & inset = tabular.getCellInset(cell);
2501                 if (inset.searchBackward(bv, str, cs, mw)) {
2502                         updateLocal(bv);
2503                         return true;
2504                 }
2505         }
2506         return false;
2507 }
2508
2509
2510 bool InsetTabular::insetAllowed(InsetOld::Code code) const
2511 {
2512         if (the_locking_inset)
2513                 return the_locking_inset->insetAllowed(code);
2514         // we return true here because if the inset is not locked someone
2515         // wants to insert something in one of our insettexts and we generally
2516         // allow to do so.
2517         return true;
2518 }
2519
2520
2521 bool InsetTabular::forceDefaultParagraphs(InsetOld const * in) const
2522 {
2523         const int cell = tabular.getCellFromInset(in);
2524
2525         if (cell != -1)
2526                 return tabular.getPWidth(cell).zero();
2527
2528         // this is a workaround for a crash (New, Insert->Tabular,
2529         // Insert->FootNote)
2530         if (!owner())
2531                 return false;
2532
2533         // well we didn't obviously find it so maybe our owner knows more
2534         BOOST_ASSERT(owner());
2535         return owner()->forceDefaultParagraphs(in);
2536 }
2537
2538
2539 bool InsetTabular::insertAsciiString(BufferView * bv, string const & buf,
2540                                      bool usePaste)
2541 {
2542         if (buf.length() <= 0)
2543                 return true;
2544
2545         int cols = 1;
2546         int rows = 1;
2547         int maxCols = 1;
2548         string::size_type len = buf.length();
2549         string::size_type p = 0;
2550
2551         while (p < len && (p = buf.find_first_of("\t\n", p)) != string::npos) {
2552                 switch (buf[p]) {
2553                 case '\t':
2554                         ++cols;
2555                         break;
2556                 case '\n':
2557                         if (p + 1 < len)
2558                                 ++rows;
2559                         maxCols = max(cols, maxCols);
2560                         cols = 1;
2561                         break;
2562                 }
2563                 ++p;
2564         }
2565         maxCols = max(cols, maxCols);
2566         LyXTabular * loctab;
2567         int cell = 0;
2568         int ocol = 0;
2569         int row = 0;
2570         if (usePaste) {
2571                 paste_tabular.reset(
2572                         new LyXTabular(bv->buffer()->params(), rows, maxCols)
2573                         );
2574
2575                 paste_tabular->setOwner(this);
2576                 loctab = paste_tabular.get();
2577                 cols = 0;
2578         } else {
2579                 loctab = &tabular;
2580                 cell = actcell;
2581                 ocol = actcol;
2582                 row = actrow;
2583         }
2584
2585         string::size_type op = 0;
2586         int cells = loctab->getNumberOfCells();
2587         p = 0;
2588         cols = ocol;
2589         rows = loctab->rows();
2590         int const columns = loctab->columns();
2591
2592         while (cell < cells && p < len && row < rows &&
2593                (p = buf.find_first_of("\t\n", p)) != string::npos)
2594         {
2595                 if (p >= len)
2596                         break;
2597                 switch (buf[p]) {
2598                 case '\t':
2599                         // we can only set this if we are not too far right
2600                         if (cols < columns) {
2601                                 InsetText & inset = loctab->getCellInset(cell);
2602                                 LyXFont const font = inset.getLyXText(bv)->
2603                                         getFont(inset.paragraphs.begin(), 0);
2604                                 inset.setText(buf.substr(op, p - op), font);
2605                                 ++cols;
2606                                 ++cell;
2607                         }
2608                         break;
2609                 case '\n':
2610                         // we can only set this if we are not too far right
2611                         if (cols < columns) {
2612                                 InsetText & inset = tabular.getCellInset(cell);
2613                                 LyXFont const font = inset.getLyXText(bv)->
2614                                         getFont(inset.paragraphs.begin(), 0);
2615                                 inset.setText(buf.substr(op, p - op), font);
2616                         }
2617                         cols = ocol;
2618                         ++row;
2619                         if (row < rows)
2620                                 cell = loctab->getCellNumber(row, cols);
2621                         break;
2622                 }
2623                 ++p;
2624                 op = p;
2625         }
2626         // check for the last cell if there is no trailing '\n'
2627         if (cell < cells && op < len) {
2628                 InsetText & inset = loctab->getCellInset(cell);
2629                 LyXFont const font = inset.getLyXText(bv)->
2630                         getFont(inset.paragraphs.begin(), 0);
2631                 inset.setText(buf.substr(op, len - op), font);
2632         }
2633
2634         return true;
2635 }
2636
2637
2638 void InsetTabular::addPreview(PreviewLoader & loader) const
2639 {
2640         int const rows = tabular.rows();
2641         int const columns = tabular.columns();
2642         for (int i = 0; i < rows; ++i)
2643                 for (int j = 0; j < columns; ++j)
2644                         tabular.getCellInset(i, j).addPreview(loader);
2645 }
2646
2647
2648 string const InsetTabularMailer::name_("tabular");
2649
2650 InsetTabularMailer::InsetTabularMailer(InsetTabular const & inset)
2651         : inset_(const_cast<InsetTabular &>(inset))
2652 {}
2653
2654
2655 string const InsetTabularMailer::inset2string(Buffer const &) const
2656 {
2657         return params2string(inset_);
2658 }
2659
2660
2661 int InsetTabularMailer::string2params(string const & in, InsetTabular & inset)
2662 {
2663         istringstream data(in);
2664         LyXLex lex(0,0);
2665         lex.setStream(data);
2666
2667 #warning CHECK verify that this is a sane value to return.
2668         if (in.empty())
2669                 return -1;
2670
2671         if (lex.isOK()) {
2672                 lex.next();
2673                 string const token = lex.getString();
2674                 if (token != name_)
2675                         return -1;
2676         }
2677
2678         int cell = -1;
2679         if (lex.isOK()) {
2680                 lex.next();
2681                 string const token = lex.getString();
2682                 if (token != "\\active_cell")
2683                         return -1;
2684                 lex.next();
2685                 cell = lex.getInteger();
2686         }
2687
2688         // This is part of the inset proper that is usually swallowed
2689         // by Buffer::readInset
2690         if (lex.isOK()) {
2691                 lex.next();
2692                 string const token = lex.getString();
2693                 if (token != "Tabular")
2694                         return -1;
2695         }
2696
2697         if (!lex.isOK())
2698                 return -1;
2699
2700         Buffer const & buffer = inset.buffer();
2701         inset.read(buffer, lex);
2702
2703         // We can't set the active cell, but we can tell the frontend
2704         // what it is.
2705         return cell;
2706 }
2707
2708
2709 string const InsetTabularMailer::params2string(InsetTabular const & inset)
2710 {
2711         Buffer const & buffer = inset.buffer();
2712
2713         ostringstream data;
2714         data << name_ << " \\active_cell " << inset.getActCell() << '\n';
2715         inset.write(buffer, data);
2716         data << "\\end_inset\n";
2717         return data.str();
2718 }