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