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