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