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