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