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