]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
a9970f440efeb959b6b7a4e80d9516c9e4390e5c
[lyx.git] / src / mathed / InsetMathGrid.cpp
1 /**
2  * \file InsetMathGrid.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12 #include <algorithm>
13
14 #include "InsetMathGrid.h"
15
16 #include "InsetMathUnknown.h"
17 #include "MathData.h"
18 #include "MathParser.h"
19 #include "MathStream.h"
20 #include "MetricsInfo.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
25 #include "CutAndPaste.h"
26 #include "FuncStatus.h"
27 #include "Cursor.h"
28 #include "FuncRequest.h"
29
30 #include "frontends/Clipboard.h"
31 #include "frontends/Painter.h"
32
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37
38 #include "support/lassert.h"
39
40 #include <sstream>
41
42 using namespace std;
43 using namespace lyx::support;
44
45
46
47 namespace lyx {
48
49 static docstring verboseHLine(int n)
50 {
51         docstring res;
52         for (int i = 0; i < n; ++i)
53                 res += "\\hline";
54         if (n)
55                 res += ' ';
56         return res;
57 }
58
59
60 static int extractInt(istream & is)
61 {
62         int num = 1;
63         is >> num;
64         return (num == 0) ? 1 : num;
65 }
66
67
68 static void resetGrid(InsetMathGrid & grid)
69 {
70         while (grid.ncols() > 1)
71                 grid.delCol(grid.ncols() - 1);
72         while (grid.nrows() > 1)
73                 grid.delRow(grid.nrows() - 1);
74         grid.cell(0).erase(0, grid.cell(0).size());
75         grid.setDefaults();
76 }
77
78
79
80 //////////////////////////////////////////////////////////////
81
82
83 InsetMathGrid::CellInfo::CellInfo()
84         : multi_(CELL_NORMAL)
85 {}
86
87
88
89 //////////////////////////////////////////////////////////////
90
91
92 InsetMathGrid::RowInfo::RowInfo()
93         : lines_(0), skip_(0), allow_newpage_(true)
94 {}
95
96
97
98 int InsetMathGrid::RowInfo::skipPixels(MetricsInfo const & mi) const
99 {
100         return crskip_.inPixels(mi.base);
101 }
102
103
104
105 //////////////////////////////////////////////////////////////
106
107
108 InsetMathGrid::ColInfo::ColInfo()
109         : align_('c'), lines_(0), skip_(0)
110 {}
111
112
113 //////////////////////////////////////////////////////////////
114
115
116 InsetMathGrid::InsetMathGrid(Buffer * buf)
117         : InsetMathNest(buf, 1),
118           rowinfo_(1 + 1),
119                 colinfo_(1 + 1),
120                 cellinfo_(1),
121                 v_align_('c')
122 {
123         setDefaults();
124 }
125
126
127 InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n)
128         : InsetMathNest(buf, m * n),
129           rowinfo_(n + 1),
130                 colinfo_(m + 1),
131                 cellinfo_(m * n),
132                 v_align_('c')
133 {
134         setDefaults();
135 }
136
137
138 InsetMathGrid::InsetMathGrid(Buffer * buf, col_type m, row_type n, char v,
139         docstring const & h)
140         : InsetMathNest(buf, m * n),
141           rowinfo_(n + 1),
142           colinfo_(m + 1),
143                 cellinfo_(m * n),
144                 v_align_(v)
145 {
146         setDefaults();
147         setVerticalAlignment(v);
148         setHorizontalAlignments(h);
149 }
150
151
152 Inset * InsetMathGrid::clone() const
153 {
154         return new InsetMathGrid(*this);
155 }
156
157
158 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
159 {
160         return col + ncols() * row;
161 }
162
163
164 void InsetMathGrid::setDefaults()
165 {
166         if (ncols() <= 0)
167                 lyxerr << "positive number of columns expected" << endl;
168         //if (nrows() <= 0)
169         //      lyxerr << "positive number of rows expected" << endl;
170         for (col_type col = 0; col < ncols(); ++col) {
171                 colinfo_[col].align_ = defaultColAlign(col);
172                 colinfo_[col].skip_  = defaultColSpace(col);
173                 colinfo_[col].special_.clear();
174         }
175         for (idx_type idx = 0; idx < nargs(); ++idx)
176                 cellinfo_[idx].multi_ = CELL_NORMAL;
177 }
178
179
180 bool InsetMathGrid::interpretString(Cursor & cur, docstring const & str)
181 {
182         if (str == "\\hline") {
183                 FuncRequest fr = FuncRequest(LFUN_INSET_MODIFY, "tabular add-hline-above");
184                 FuncStatus status;
185                 if (getStatus(cur, fr, status)) {
186                         if (status.enabled()) {
187                                 rowinfo_[cur.row()].lines_++;
188                                 return true;
189                         }
190                 }
191         }
192         return InsetMathNest::interpretString(cur, str);
193 }
194
195
196 void InsetMathGrid::setHorizontalAlignments(docstring const & hh)
197 {
198         col_type col = 0;
199         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it) {
200                 char_type c = *it;
201                 if (c == '|') {
202                         colinfo_[col].lines_++;
203                 } else if ((c == 'p' || c == 'm' || c == 'b'||
204                             c == '!' || c == '@' || c == '>' || c == '<') &&
205                            it + 1 != hh.end() && *(it + 1) == '{') {
206                         // @{decl.} and p{width} are standard LaTeX, the
207                         // others are extensions by array.sty
208                         bool const newcolumn = c == 'p' || c == 'm' || c == 'b';
209                         if (newcolumn) {
210                                 // this declares a new column
211                                 if (col >= ncols())
212                                         // Only intercolumn stuff is allowed
213                                         // in the last dummy column
214                                         break;
215                                 colinfo_[col].align_ = 'l';
216                         } else {
217                                 // this is intercolumn stuff
218                                 if (colinfo_[col].special_.empty())
219                                         // Overtake possible lines
220                                         colinfo_[col].special_ = docstring(colinfo_[col].lines_, '|');
221                         }
222                         int brace_open = 0;
223                         int brace_close = 0;
224                         while (it != hh.end()) {
225                                 c = *it;
226                                 colinfo_[col].special_ += c;
227                                 if (c == '{')
228                                         ++brace_open;
229                                 else if (c == '}')
230                                         ++brace_close;
231                                 ++it;
232                                 if (brace_open > 0 && brace_open == brace_close)
233                                         break;
234                         }
235                         --it;
236                         if (newcolumn) {
237                                 colinfo_[col].lines_ = count(
238                                         colinfo_[col].special_.begin(),
239                                         colinfo_[col].special_.end(), '|');
240                                 LYXERR(Debug::MATHED, "special column separator: `"
241                                         << to_utf8(colinfo_[col].special_) << '\'');
242                                 ++col;
243                                 colinfo_[col].lines_ = 0;
244                                 colinfo_[col].special_.clear();
245                         }
246                 } else if (col >= ncols()) {
247                         // Only intercolumn stuff is allowed in the last
248                         // dummy column
249                         break;
250                 } else if (c == 'c' || c == 'l' || c == 'r') {
251                         colinfo_[col].align_ = static_cast<char>(c);
252                         if (!colinfo_[col].special_.empty()) {
253                                 colinfo_[col].special_ += c;
254                                 colinfo_[col].lines_ = count(
255                                                 colinfo_[col].special_.begin(),
256                                                 colinfo_[col].special_.end(), '|');
257                                 LYXERR(Debug::MATHED, "special column separator: `"
258                                         << to_utf8(colinfo_[col].special_) << '\'');
259                         }
260                         ++col;
261                         colinfo_[col].lines_ = 0;
262                         colinfo_[col].special_.clear();
263                 } else {
264                         lyxerr << "unknown column separator: '" << c << "'" << endl;
265                 }
266         }
267
268 /*
269         col_type n = hh.size();
270         if (n > ncols())
271                 n = ncols();
272         for (col_type col = 0; col < n; ++col)
273                 colinfo_[col].align_ = hh[col];
274 */
275 }
276
277
278 InsetMathGrid::col_type InsetMathGrid::guessColumns(docstring const & hh)
279 {
280         col_type col = 0;
281         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it)
282                 if (*it == 'c' || *it == 'l' || *it == 'r'||
283                     *it == 'p' || *it == 'm' || *it == 'b')
284                         ++col;
285         // let's have at least one column, even if we did not recognize its
286         // alignment
287         if (col == 0)
288                 col = 1;
289         return col;
290 }
291
292
293 void InsetMathGrid::setHorizontalAlignment(char h, col_type col)
294 {
295         colinfo_[col].align_ = h;
296         if (!colinfo_[col].special_.empty()) {
297                 char_type & c = colinfo_[col].special_[colinfo_[col].special_.size() - 1];
298                 if (c == 'l' || c == 'c' || c == 'r')
299                         c = h;
300         }
301         // FIXME: Change alignment of p, m and b columns, too
302 }
303
304
305 char InsetMathGrid::horizontalAlignment(col_type col) const
306 {
307         return colinfo_[col].align_;
308 }
309
310
311 docstring InsetMathGrid::horizontalAlignments() const
312 {
313         docstring res;
314         for (col_type col = 0; col < ncols(); ++col) {
315                 if (colinfo_[col].special_.empty()) {
316                         res += docstring(colinfo_[col].lines_, '|');
317                         res += colinfo_[col].align_;
318                 } else
319                         res += colinfo_[col].special_;
320         }
321         if (colinfo_[ncols()].special_.empty())
322                 return res + docstring(colinfo_[ncols()].lines_, '|');
323         return res + colinfo_[ncols()].special_;
324 }
325
326
327 void InsetMathGrid::setVerticalAlignment(char c)
328 {
329         v_align_ = c;
330 }
331
332
333 char InsetMathGrid::verticalAlignment() const
334 {
335         return v_align_;
336 }
337
338
339 InsetMathGrid::col_type InsetMathGrid::ncols() const
340 {
341         return colinfo_.size() - 1;
342 }
343
344
345 InsetMathGrid::row_type InsetMathGrid::nrows() const
346 {
347         return rowinfo_.size() - 1;
348 }
349
350
351 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
352 {
353         return idx % ncols();
354 }
355
356
357 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
358 {
359         return idx / ncols();
360 }
361
362
363 InsetMathGrid::col_type InsetMathGrid::ncellcols(idx_type idx) const
364 {
365         col_type cols = 1;
366         if (cellinfo_[idx].multi_ == CELL_NORMAL)
367                 return cols;
368         // If the cell at idx is already CELL_PART_OF_MULTICOLUMN we return
369         // the number of remaining columns, not the ones of the complete
370         // multicolumn cell. This makes it possible to always go to the next
371         // cell with idx + ncellcols(idx) - 1.
372         row_type const r = row(idx);
373         while (idx+cols < nargs() && row(idx+cols) == r &&
374                cellinfo_[idx+cols].multi_ == CELL_PART_OF_MULTICOLUMN)
375                 cols++;
376         return cols;
377 }
378
379
380 void InsetMathGrid::vcrskip(Length const & crskip, row_type row)
381 {
382         rowinfo_[row].crskip_ = crskip;
383 }
384
385
386 Length InsetMathGrid::vcrskip(row_type row) const
387 {
388         return rowinfo_[row].crskip_;
389 }
390
391
392 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
393 {
394         // let the cells adjust themselves
395         for (idx_type i = 0; i < nargs(); ++i) {
396                 if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
397                         Dimension dimc;
398                         cell(i).metrics(mi, dimc);
399                 }
400         }
401
402         BufferView & bv = *mi.base.bv;
403
404         // compute absolute sizes of vertical structure
405         for (row_type row = 0; row < nrows(); ++row) {
406                 int asc  = 0;
407                 int desc = 0;
408                 for (col_type col = 0; col < ncols(); ++col) {
409                         idx_type const i = index(row, col);
410                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
411                                 Dimension const & dimc = cell(i).dimension(bv);
412                                 asc  = max(asc,  dimc.asc);
413                                 desc = max(desc, dimc.des);
414                         }
415                 }
416                 rowinfo_[row].ascent_  = asc;
417                 rowinfo_[row].descent_ = desc;
418         }
419         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
420         rowinfo_[nrows()].ascent_  = 0;
421         rowinfo_[nrows()].descent_ = 0;
422
423         // compute vertical offsets
424         rowinfo_[0].offset_ = 0;
425         for (row_type row = 1; row <= nrows(); ++row) {
426                 rowinfo_[row].offset_ =
427                         rowinfo_[row - 1].offset_ +
428                         rowinfo_[row - 1].descent_ +
429                         rowinfo_[row - 1].skipPixels(mi) +
430                         rowsep() +
431                         rowinfo_[row].lines_ * hlinesep() +
432                         rowinfo_[row].ascent_;
433         }
434
435         // adjust vertical offset
436         int h = 0;
437         switch (v_align_) {
438                 case 't':
439                         h = 0;
440                         break;
441                 case 'b':
442                         h = rowinfo_[nrows() - 1].offset_;
443                         break;
444                 default:
445                         h = rowinfo_[nrows() - 1].offset_ / 2;
446         }
447         for (row_type row = 0; row <= nrows(); ++row)
448                 rowinfo_[row].offset_ -= h;
449
450
451         // multicolumn cell widths, as a map from first column to width in a
452         // vector of last columns.
453         // This is only used if the grid has more than one row, since for
454         // one-row grids multicolumn cells do not need special handling
455         vector<map<col_type, int> > mcolwidths(ncols());
456
457         // compute absolute sizes of horizontal structure
458         for (col_type col = 0; col < ncols(); ++col) {
459                 int wid = 0;
460                 for (row_type row = 0; row < nrows(); ++row) {
461                         idx_type const i = index(row, col);
462                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
463                                 int const w = cell(i).dimension(bv).wid;
464                                 col_type const cols = ncellcols(i);
465                                 if (cols > 1 && nrows() > 1) {
466                                         col_type last = col+cols-1;
467                                         LASSERT(last < ncols(), last = ncols()-1);
468                                         map<col_type, int>::iterator it =
469                                                 mcolwidths[last].find(col);
470                                         if (it == mcolwidths[last].end())
471                                                 mcolwidths[last][col] = w;
472                                         else
473                                                 it->second = max(it->second, w);
474                                 } else
475                                         wid = max(wid, w);
476                         }
477                 }
478                 colinfo_[col].width_ = wid;
479         }
480         colinfo_[ncols()].width_  = 0;
481
482         // compute horizontal offsets
483         colinfo_[0].offset_ = border();
484         for (col_type col = 1; col <= ncols(); ++col) {
485                 colinfo_[col].offset_ =
486                         colinfo_[col - 1].offset_ +
487                         colinfo_[col - 1].width_ +
488                         colinfo_[col - 1].skip_ +
489                         colsep() +
490                         colinfo_[col].lines_ * vlinesep();
491         }
492
493         // increase column widths for multicolumn cells if needed
494         // FIXME: multicolumn lines are not yet considered
495         for (col_type last = 0; last < ncols(); ++last) {
496                 map<col_type, int> const & widths = mcolwidths[last];
497                 // We increase the width of the last column of the multicol
498                 // cell (some sort of left alignment). Since we iterate through
499                 // the last and the first columns from left to right, we ensure
500                 // that increased widths of previous columns are correctly
501                 // taken into account for later columns, thus preventing
502                 // unneeded width increasing.
503                 for (map<col_type, int>::const_iterator it = widths.begin();
504                      it != widths.end(); ++it) {
505                         int const wid = it->second;
506                         col_type const first = it->first;
507                         int const nextoffset =
508                                 colinfo_[first].offset_ +
509                                 wid +
510                                 colinfo_[last].skip_ +
511                                 colsep() +
512                                 colinfo_[last+1].lines_ * vlinesep();
513                         int const dx = nextoffset - colinfo_[last+1].offset_;
514                         if (dx > 0) {
515                                 colinfo_[last].width_ += dx;
516                                 for (col_type col = last + 1; col <= ncols(); ++col)
517                                         colinfo_[col].offset_ += dx;
518                         }
519                 }
520         }
521
522
523         dim.wid = colinfo_[ncols() - 1].offset_
524                 + colinfo_[ncols() - 1].width_
525                 + vlinesep() * colinfo_[ncols()].lines_
526                 + border();
527
528         dim.asc = - rowinfo_[0].offset_
529                 + rowinfo_[0].ascent_
530                 + hlinesep() * rowinfo_[0].lines_
531                 + border();
532
533         dim.des = rowinfo_[nrows() - 1].offset_
534                 + rowinfo_[nrows() - 1].descent_
535                 + hlinesep() * rowinfo_[nrows()].lines_
536                 + border();
537
538
539 /*
540         // Increase ws_[i] for 'R' columns (except the first one)
541         for (int i = 1; i < nc_; ++i)
542                 if (align_[i] == 'R')
543                         ws_[i] += 10 * df_width;
544         // Increase ws_[i] for 'C' column
545         if (align_[0] == 'C')
546                 if (ws_[0] < 7 * workwidth / 8)
547                         ws_[0] = 7 * workwidth / 8;
548
549         // Adjust local tabs
550         width = colsep();
551         for (cxrow = row_.begin(); cxrow; ++cxrow) {
552                 int rg = COLSEP;
553                 int lf = 0;
554                 for (int i = 0; i < nc_; ++i) {
555                         bool isvoid = false;
556                         if (cxrow->getTab(i) <= 0) {
557                                 cxrow->setTab(i, df_width);
558                                 isvoid = true;
559                         }
560                         switch (align_[i]) {
561                         case 'l':
562                                 lf = 0;
563                                 break;
564                         case 'c':
565                                 lf = (ws_[i] - cxrow->getTab(i))/2;
566                                 break;
567                         case 'r':
568                         case 'R':
569                                 lf = ws_[i] - cxrow->getTab(i);
570                                 break;
571                         case 'C':
572                                 if (cxrow == row_.begin())
573                                         lf = 0;
574                                 else if (cxrow.is_last())
575                                         lf = ws_[i] - cxrow->getTab(i);
576                                 else
577                                         lf = (ws_[i] - cxrow->getTab(i))/2;
578                                 break;
579                         }
580                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
581                         cxrow->setTab(i, lf + rg);
582                         rg = ws_[i] - ww + colsep();
583                         if (cxrow == row_.begin())
584                                 width += ws_[i] + colsep();
585                 }
586                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
587         }
588 */
589         metricsMarkers2(dim);
590         // Cache the inset dimension.
591         setDimCache(mi, dim);
592 }
593
594
595 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
596 {
597         drawWithMargin(pi, x, y, 1, 1);
598 }
599
600
601 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
602         int lmargin, int rmargin) const
603 {
604         Dimension const dim = dimension(*pi.base.bv);
605         BufferView const & bv = *pi.base.bv;
606
607         for (idx_type idx = 0; idx < nargs(); ++idx) {
608                 if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN) {
609                         cell(idx).draw(pi,
610                                 x + lmargin + cellXOffset(bv, idx),
611                                 y + cellYOffset(idx));
612
613                         // draw inner lines cell by cell because of possible multicolumns
614                         // FIXME: multicolumn lines are not yet considered
615                         row_type const r = row(idx);
616                         col_type const c = col(idx);
617                         if (r > 0 && r < nrows()) {
618                                 for (unsigned int i = 0; i < rowinfo_[r].lines_; ++i) {
619                                         int yy = y + rowinfo_[r].offset_
620                                                 - rowinfo_[r].ascent_
621                                                 - i * hlinesep()
622                                                 - hlinesep()/2 - rowsep()/2;
623                                         pi.pain.line(
624                                                 x + lmargin + colinfo_[c].offset_,
625                                                 yy,
626                                                 x + lmargin + colinfo_[c+1].offset_,
627                                                 yy, Color_foreground);
628                                 }
629                         }
630                         if (c > 0 && c < ncols()) {
631                                 for (unsigned int i = 0; i < colinfo_[c].lines_; ++i) {
632                                         int xx = x + lmargin
633                                                 + colinfo_[c].offset_
634                                                 - i * vlinesep()
635                                                 - vlinesep()/2 - colsep()/2;
636                                         pi.pain.line(xx,
637                                                 rowinfo_[r].offset_ - rowinfo_[r].ascent_,
638                                                 xx,
639                                                 rowinfo_[r].offset_ + rowinfo_[r].descent_,
640                                                 Color_foreground);
641                                 }
642                         }
643                 }
644         }
645
646         // draw outer lines in one go
647         for (row_type row = 0; row <= nrows(); row += nrows())
648                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
649                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
650                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
651                         pi.pain.line(x + lmargin + 1, yy,
652                                      x + dim.width() - rmargin - 1, yy,
653                                      Color_foreground);
654                 }
655
656         for (col_type col = 0; col <= ncols(); col += ncols())
657                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
658                         int xx = x + lmargin + colinfo_[col].offset_
659                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
660                         pi.pain.line(xx, y - dim.ascent() + 1,
661                                      xx, y + dim.descent() - 1,
662                                      Color_foreground);
663                 }
664         drawMarkers2(pi, x, y);
665 }
666
667
668 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
669 {
670         // let the cells adjust themselves
671         for (idx_type i = 0; i < nargs(); ++i)
672                 if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
673                         cell(i).metricsT(mi, dim);
674
675         // compute absolute sizes of vertical structure
676         for (row_type row = 0; row < nrows(); ++row) {
677                 int asc  = 0;
678                 int desc = 0;
679                 for (col_type col = 0; col < ncols(); ++col) {
680                         idx_type const i = index(row, col);
681                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
682                                 //MathData const & c = cell(i);
683                                 // FIXME: BROKEN!
684                                 Dimension dimc;
685                                 asc  = max(asc,  dimc.ascent());
686                                 desc = max(desc, dimc.descent());
687                         }
688                 }
689                 rowinfo_[row].ascent_  = asc;
690                 rowinfo_[row].descent_ = desc;
691         }
692         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
693         rowinfo_[nrows()].ascent_  = 0;
694         rowinfo_[nrows()].descent_ = 0;
695
696         // compute vertical offsets
697         rowinfo_[0].offset_ = 0;
698         for (row_type row = 1; row <= nrows(); ++row) {
699                 rowinfo_[row].offset_  =
700                         rowinfo_[row - 1].offset_  +
701                         rowinfo_[row - 1].descent_ +
702                         //rowinfo_[row - 1].skipPixels(mi) +
703                         1 + //rowsep() +
704                         //rowinfo_[row].lines_ * hlinesep() +
705                         rowinfo_[row].ascent_;
706         }
707
708         // adjust vertical offset
709         int h = 0;
710         switch (v_align_) {
711                 case 't':
712                         h = 0;
713                         break;
714                 case 'b':
715                         h = rowinfo_[nrows() - 1].offset_;
716                         break;
717                 default:
718                         h = rowinfo_[nrows() - 1].offset_ / 2;
719         }
720         for (row_type row = 0; row <= nrows(); ++row)
721                 rowinfo_[row].offset_ -= h;
722
723
724         // compute absolute sizes of horizontal structure
725         for (col_type col = 0; col < ncols(); ++col) {
726                 int wid = 0;
727                 for (row_type row = 0; row < nrows(); ++row) {
728                         // FIXME: BROKEN!
729                         //idx_type const i = index(row, col);
730                         //if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN)
731                         //      wid = max(wid, cell(i).width());
732                 }
733                 colinfo_[col].width_ = wid;
734         }
735         colinfo_[ncols()].width_  = 0;
736
737         // compute horizontal offsets
738         colinfo_[0].offset_ = border();
739         for (col_type col = 1; col <= ncols(); ++col) {
740                 colinfo_[col].offset_ =
741                         colinfo_[col - 1].offset_ +
742                         colinfo_[col - 1].width_ +
743                         colinfo_[col - 1].skip_ +
744                         1 ; //colsep() +
745                         //colinfo_[col].lines_ * vlinesep();
746         }
747
748
749         dim.wid  =  colinfo_[ncols() - 1].offset_
750                        + colinfo_[ncols() - 1].width_
751                  //+ vlinesep() * colinfo_[ncols()].lines_
752                        + 2;
753
754         dim.asc  = -rowinfo_[0].offset_
755                        + rowinfo_[0].ascent_
756                  //+ hlinesep() * rowinfo_[0].lines_
757                        + 1;
758
759         dim.des  =  rowinfo_[nrows() - 1].offset_
760                        + rowinfo_[nrows() - 1].descent_
761                  //+ hlinesep() * rowinfo_[nrows()].lines_
762                        + 1;
763 }
764
765
766 void InsetMathGrid::drawT(TextPainter & /*pain*/, int /*x*/, int /*y*/) const
767 {
768 //      for (idx_type idx = 0; idx < nargs(); ++idx)
769 //              if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
770 //                      cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
771 }
772
773
774 void InsetMathGrid::updateBuffer(ParIterator const & it, UpdateType utype)
775 {
776         // pass down
777         for (idx_type idx = 0; idx < nargs(); ++idx)
778                 if (cellinfo_[idx].multi_ != CELL_PART_OF_MULTICOLUMN)
779                         cell(idx).updateBuffer(it, utype);
780 }
781
782
783 docstring InsetMathGrid::eolString(row_type row, bool fragile,
784                 bool /*latex*/, bool last_eoln) const
785 {
786         docstring eol;
787
788         if (!rowinfo_[row].crskip_.zero())
789                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
790         else if(!rowinfo_[row].allow_newpage_)
791                 eol += '*';
792
793         // make sure an upcoming '[' does not break anything
794         if (row + 1 < nrows()) {
795                 MathData const & c = cell(index(row + 1, 0));
796                 if (!c.empty() && c.front()->getChar() == '[')
797                         //eol += "[0pt]";
798                         eol += "{}";
799         }
800
801         // only add \\ if necessary
802         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !last_eoln))
803                 return docstring();
804
805         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
806 }
807
808
809 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
810 {
811         if (col + 1 == lastcol)
812                 return docstring();
813         return from_ascii(" & ");
814 }
815
816
817 void InsetMathGrid::addRow(row_type row)
818 {
819         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
820         cells_.insert
821                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathData());
822         cellinfo_.insert
823                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
824 }
825
826
827 void InsetMathGrid::delRow(row_type row)
828 {
829         if (nrows() == 1)
830                 return;
831
832         cells_type::iterator it = cells_.begin() + row * ncols();
833         cells_.erase(it, it + ncols());
834
835         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
836         cellinfo_.erase(jt, jt + ncols());
837
838         rowinfo_.erase(rowinfo_.begin() + row);
839 }
840
841
842 void InsetMathGrid::copyRow(row_type row)
843 {
844         addRow(row);
845         for (col_type col = 0; col < ncols(); ++col)
846                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
847 }
848
849
850 void InsetMathGrid::swapRow(row_type row)
851 {
852         if (nrows() == 1)
853                 return;
854         if (row + 1 == nrows())
855                 --row;
856         for (col_type col = 0; col < ncols(); ++col)
857                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
858 }
859
860
861 void InsetMathGrid::addCol(col_type newcol)
862 {
863         const col_type nc = ncols();
864         const row_type nr = nrows();
865         cells_type new_cells((nc + 1) * nr);
866         vector<CellInfo> new_cellinfo((nc + 1) * nr);
867
868         for (row_type row = 0; row < nr; ++row)
869                 for (col_type col = 0; col < nc; ++col) {
870                         new_cells[row * (nc + 1) + col + (col >= newcol)]
871                                 = cells_[row * nc + col];
872                         new_cellinfo[row * (nc + 1) + col + (col >= newcol)]
873                                 = cellinfo_[row * nc + col];
874                 }
875         swap(cells_, new_cells);
876         swap(cellinfo_, new_cellinfo);
877
878         ColInfo inf;
879         inf.skip_  = defaultColSpace(newcol);
880         inf.align_ = defaultColAlign(newcol);
881         colinfo_.insert(colinfo_.begin() + newcol, inf);
882 }
883
884
885 void InsetMathGrid::delCol(col_type col)
886 {
887         if (ncols() == 1)
888                 return;
889
890         cells_type tmpcells;
891         vector<CellInfo> tmpcellinfo;
892         for (col_type i = 0; i < nargs(); ++i)
893                 if (i % ncols() != col) {
894                         tmpcells.push_back(cells_[i]);
895                         tmpcellinfo.push_back(cellinfo_[i]);
896                 }
897         swap(cells_, tmpcells);
898         swap(cellinfo_, tmpcellinfo);
899
900         colinfo_.erase(colinfo_.begin() + col);
901 }
902
903
904 void InsetMathGrid::copyCol(col_type col)
905 {
906         addCol(col+1);
907         for (row_type row = 0; row < nrows(); ++row)
908                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
909 }
910
911
912 void InsetMathGrid::swapCol(col_type col)
913 {
914         if (ncols() == 1)
915                 return;
916         if (col + 1 == ncols())
917                 --col;
918         for (row_type row = 0; row < nrows(); ++row)
919                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
920 }
921
922
923 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
924 {
925         if (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN)
926                 return 0;
927         col_type c = col(idx);
928         int x = colinfo_[c].offset_;
929         char align = displayColAlign(idx);
930         Dimension const & celldim = cell(idx).dimension(bv);
931         if (align == 'r' || align == 'R')
932                 x += cellWidth(idx) - celldim.wid;
933         if (align == 'c' || align == 'C')
934                 x += (cellWidth(idx) - celldim.wid) / 2;
935         return x;
936 }
937
938
939 int InsetMathGrid::cellYOffset(idx_type idx) const
940 {
941         return rowinfo_[row(idx)].offset_;
942 }
943
944
945 int InsetMathGrid::cellWidth(idx_type idx) const
946 {
947         switch (cellinfo_[idx].multi_) {
948         case CELL_NORMAL:
949                 return colinfo_[col(idx)].width_;
950         case CELL_BEGIN_OF_MULTICOLUMN: {
951                 col_type c1 = col(idx);
952                 col_type c2 = c1 + ncellcols(idx);
953                 return colinfo_[c2].offset_
954                         - colinfo_[c1].offset_
955                         - colinfo_[c2].skip_
956                         - colsep()
957                         - colinfo_[c2].lines_ * vlinesep();
958         }
959         case CELL_PART_OF_MULTICOLUMN:
960                 return 0;
961         }
962         return 0;
963 }
964
965
966 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
967 {
968         if (up) {
969                 if (cur.row() == 0)
970                         return false;
971                 cur.idx() -= ncols();
972         } else {
973                 if (cur.row() + 1 >= nrows())
974                         return false;
975                 cur.idx() += ncols();
976         }
977         // If we are in a multicolumn cell, move to the "real" cell
978         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
979                 LASSERT(cur.idx() > 0, return false);
980                 --cur.idx();
981         }
982         cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
983         return true;
984 }
985
986
987 bool InsetMathGrid::idxBackward(Cursor & cur) const
988 {
989         // leave matrix if at the front edge
990         if (cur.col() == 0)
991                 return false;
992         --cur.idx();
993         // If we are in a multicolumn cell, move to the "real" cell
994         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
995                 LASSERT(cur.idx() > 0, return false);
996                 --cur.idx();
997         }
998         cur.pos() = cur.lastpos();
999         return true;
1000 }
1001
1002
1003 bool InsetMathGrid::idxForward(Cursor & cur) const
1004 {
1005         // leave matrix if at the back edge
1006         if (cur.col() + 1 == ncols())
1007                 return false;
1008         ++cur.idx();
1009         // If we are in a multicolumn cell, move to the next cell
1010         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1011                 // leave matrix if at the back edge
1012                 if (cur.col() + 1 == ncols())
1013                         return false;
1014                 ++cur.idx();
1015         }
1016         cur.pos() = 0;
1017         return true;
1018 }
1019
1020
1021 bool InsetMathGrid::idxFirst(Cursor & cur) const
1022 {
1023         switch (v_align_) {
1024                 case 't':
1025                         cur.idx() = 0;
1026                         break;
1027                 case 'b':
1028                         cur.idx() = (nrows() - 1) * ncols();
1029                         break;
1030                 default:
1031                         cur.idx() = ((nrows() - 1) / 2) * ncols();
1032         }
1033         // If we are in a multicolumn cell, move to the "real" cell
1034         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1035                 LASSERT(cur.idx() > 0, return false);
1036                 --cur.idx();
1037         }
1038         cur.pos() = 0;
1039         return true;
1040 }
1041
1042
1043 bool InsetMathGrid::idxLast(Cursor & cur) const
1044 {
1045         switch (v_align_) {
1046                 case 't':
1047                         cur.idx() = ncols() - 1;
1048                         break;
1049                 case 'b':
1050                         cur.idx() = nargs() - 1;
1051                         break;
1052                 default:
1053                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
1054         }
1055         // If we are in a multicolumn cell, move to the "real" cell
1056         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1057                 LASSERT(cur.idx() > 0, return false);
1058                 --cur.idx();
1059         }
1060         cur.pos() = cur.lastpos();
1061         return true;
1062 }
1063
1064
1065 bool InsetMathGrid::idxDelete(idx_type & idx)
1066 {
1067         // nothing to do if we have just one row
1068         if (nrows() == 1)
1069                 return false;
1070
1071         // nothing to do if we are in the middle of the last row of the inset
1072         if (idx + ncols() > nargs())
1073                 return false;
1074
1075         // try to delete entire sequence of ncols() empty cells if possible
1076         for (idx_type i = idx; i < idx + ncols(); ++i)
1077                 if (!cell(i).empty())
1078                         return false;
1079
1080         // move cells if necessary
1081         for (idx_type i = index(row(idx), 0); i < idx; ++i)
1082                 swap(cell(i), cell(i + ncols()));
1083
1084         delRow(row(idx));
1085
1086         if (idx >= nargs())
1087                 idx = nargs() - 1;
1088
1089         // undo effect of Ctrl-Tab (i.e. pull next cell)
1090         //if (idx + 1 != nargs())
1091         //      cell(idx).swap(cell(idx + 1));
1092
1093         // we handled the event..
1094         return true;
1095 }
1096
1097
1098 // reimplement old behaviour when pressing Delete in the last position
1099 // of a cell
1100 void InsetMathGrid::idxGlue(idx_type idx)
1101 {
1102         col_type c = col(idx);
1103         if (c + 1 == ncols()) {
1104                 if (row(idx) + 1 != nrows()) {
1105                         for (col_type cc = 0; cc < ncols(); ++cc)
1106                                 cell(idx).append(cell(idx + cc + 1));
1107                         delRow(row(idx) + 1);
1108                 }
1109         } else {
1110                 idx_type idx_next = idx + 1;
1111                 while (idx_next < nargs() &&
1112                        cellinfo_[idx_next].multi_ == CELL_PART_OF_MULTICOLUMN)
1113                         ++idx_next;
1114                 if (idx_next < nargs())
1115                         cell(idx).append(cell(idx_next));
1116                 col_type oldcol = c + 1;
1117                 for (col_type cc = c + 2; cc < ncols(); ++cc)
1118                         cell(idx - oldcol + cc) = cell(idx - oldcol + 1 + cc);
1119                 cell(idx - c + ncols() - 1).clear();
1120         }
1121 }
1122
1123
1124 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
1125 {
1126         return rowinfo_[row];
1127 }
1128
1129
1130 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
1131 {
1132         return rowinfo_[row];
1133 }
1134
1135
1136 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
1137 {
1138         row_type const ri = row(idx);
1139         row_type const r1 = min(row(from), row(to));
1140         row_type const r2 = max(row(from), row(to));
1141         col_type const ci = col(idx);
1142         col_type const c1 = min(col(from), col(to));
1143         col_type const c2 = max(col(from), col(to));
1144         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
1145 }
1146
1147
1148 void InsetMathGrid::normalize(NormalStream & os) const
1149 {
1150         os << "[grid ";
1151         for (row_type row = 0; row < nrows(); ++row) {
1152                 os << "[row ";
1153                 for (col_type col = 0; col < ncols(); ++col) {
1154                         idx_type const i = index(row, col);
1155                         switch (cellinfo_[i].multi_) {
1156                         case CELL_NORMAL:
1157                                 os << "[cell " << cell(i) << ']';
1158                                 break;
1159                         case CELL_BEGIN_OF_MULTICOLUMN:
1160                                 os << "[cell colspan="
1161                                    << static_cast<int>(ncellcols(i)) << ' '
1162                                    << cell(i) << ']';
1163                                 break;
1164                         case CELL_PART_OF_MULTICOLUMN:
1165                                 break;
1166                         }
1167                 }
1168                 os << ']';
1169         }
1170         os << ']';
1171 }
1172
1173
1174 void InsetMathGrid::mathmlize(MathStream & os) const
1175 {
1176         bool const havetable = nrows() > 1 || ncols() > 1;
1177         if (havetable)
1178                 os << MTag("mtable");
1179         char const * const celltag = havetable ? "mtd" : "mrow";
1180         for (row_type row = 0; row < nrows(); ++row) {
1181                 if (havetable)
1182                         os << MTag("mtr");
1183                 for (col_type col = 0; col < ncols(); ++col) {
1184                         idx_type const i = index(row, col);
1185                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1186                                 col_type const cellcols = ncellcols(i);
1187                                 ostringstream attr;
1188                                 if (havetable && cellcols > 1)
1189                                         attr << "colspan='" << cellcols << '\'';
1190                                 os << MTag(celltag, attr.str());
1191                                 os << cell(index(row, col));
1192                                 os << ETag(celltag);
1193                         }
1194                 }
1195                 if (havetable)
1196                         os << ETag("mtr");
1197         }
1198         if (havetable)
1199                 os << ETag("mtable");
1200 }
1201
1202
1203 // FIXME XHTML
1204 // We need to do something about alignment here.
1205 void InsetMathGrid::htmlize(HtmlStream & os, string attrib) const
1206 {
1207         bool const havetable = nrows() > 1 || ncols() > 1;
1208         if (!havetable) {
1209                 os << cell(index(0, 0));
1210                 return;
1211         }
1212         os << MTag("table", attrib);
1213         for (row_type row = 0; row < nrows(); ++row) {
1214                 os << MTag("tr");
1215                 for (col_type col = 0; col < ncols(); ++col) {
1216                         idx_type const i = index(row, col);
1217                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1218                                 col_type const cellcols = ncellcols(i);
1219                                 ostringstream attr;
1220                                 if (cellcols > 1)
1221                                         attr << "colspan='" << cellcols << '\'';
1222                                 os << MTag("td", attr.str());
1223                                 os << cell(index(row, col));
1224                                 os << ETag("td");
1225                         }
1226                 }
1227                 os << ETag("tr");
1228         }
1229         os << ETag("table");
1230 }
1231
1232
1233 void InsetMathGrid::htmlize(HtmlStream & os) const
1234 {
1235         htmlize(os, "class='mathtable'");
1236 }
1237
1238
1239 void InsetMathGrid::write(WriteStream & os) const
1240 {
1241         write(os, 0, 0, nrows(), ncols());
1242 }
1243
1244 void InsetMathGrid::write(WriteStream & os,
1245                           row_type beg_row, col_type beg_col,
1246                           row_type end_row, col_type end_col) const
1247 {
1248         MathEnsurer ensurer(os, false);
1249         docstring eol;
1250         for (row_type row = beg_row; row < end_row; ++row) {
1251                 os << verboseHLine(rowinfo_[row].lines_);
1252                 // don't write & and empty cells at end of line,
1253                 // unless there are vertical lines
1254                 col_type lastcol = 0;
1255                 bool emptyline = true;
1256                 bool last_eoln = true;
1257                 for (col_type col = beg_col; col < end_col; ++col) {
1258                         idx_type const idx = index(row, col);
1259                         bool const empty_cell = cell(idx).empty();
1260                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL)
1261                                 last_eoln = false;
1262                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL ||
1263                             colinfo_[col + 1].lines_) {
1264                                 lastcol = col + 1;
1265                                 emptyline = false;
1266                         }
1267                 }
1268                 for (col_type col = beg_col; col < lastcol;) {
1269                         int nccols = 1;
1270                         idx_type const idx = index(row, col);
1271                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1272                                 size_t s = col + 1;
1273                                 while (s < ncols() &&
1274                                        cellinfo_[index(row, s)].multi_ == CELL_PART_OF_MULTICOLUMN)
1275                                         s++;
1276                                 nccols = s - col;
1277                                 os << "\\multicolumn{" << nccols
1278                                    << "}{" << cellinfo_[idx].align_
1279                                    << "}{";
1280                         }
1281                         os << cell(idx);
1282                         if (os.pendingBrace())
1283                                 ModeSpecifier specifier(os, TEXT_MODE);
1284                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1285                                 os << '}';
1286                         os << eocString(col + nccols - 1, lastcol);
1287                         col += nccols;
1288                 }
1289                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1290                 os << eol;
1291                 // append newline only if line wasn't completely empty
1292                 // and the formula is not written on a single line
1293                 bool const empty = emptyline && eol.empty();
1294                 if (!empty && nrows() > 1)
1295                         os << "\n";
1296         }
1297         // @TODO use end_row instead of nrows() ?
1298         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1299         if (!s.empty()) {
1300                 if (eol.empty()) {
1301                         if (os.fragile())
1302                                 os << "\\protect";
1303                         os << "\\\\";
1304                 }
1305                 os << s;
1306         }
1307 }
1308
1309
1310 int InsetMathGrid::colsep() const
1311 {
1312         return 6;
1313 }
1314
1315
1316 int InsetMathGrid::rowsep() const
1317 {
1318         return 6;
1319 }
1320
1321
1322 int InsetMathGrid::hlinesep() const
1323 {
1324         return 3;
1325 }
1326
1327
1328 int InsetMathGrid::vlinesep() const
1329 {
1330         return 3;
1331 }
1332
1333
1334 int InsetMathGrid::border() const
1335 {
1336         return 1;
1337 }
1338
1339
1340 void InsetMathGrid::splitCell(Cursor & cur)
1341 {
1342         if (cur.idx() == cur.lastidx())
1343                 return;
1344         MathData ar = cur.cell();
1345         ar.erase(0, cur.pos());
1346         cur.cell().erase(cur.pos(), cur.lastpos());
1347         ++cur.idx();
1348         while (cur.idx() << nargs() &&
1349                cellinfo_[cur.idx()].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1350                 ++cur.idx();
1351         cur.pos() = 0;
1352         cur.cell().insert(0, ar);
1353 }
1354
1355
1356 char InsetMathGrid::displayColAlign(idx_type idx) const
1357 {
1358         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1359                 // align_ may also contain lines like "||r|", so this is
1360                 // not complete, but we catch at least the simple cases.
1361                 if (cellinfo_[idx].align_ == "c")
1362                         return 'c';
1363                 if (cellinfo_[idx].align_ == "l")
1364                         return 'l';
1365                 if (cellinfo_[idx].align_ == "r")
1366                         return 'r';
1367         }
1368         return colinfo_[col(idx)].align_;
1369 }
1370
1371
1372 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1373 {
1374         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1375
1376         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1377
1378         FuncCode const act = cmd.action();
1379         switch (act) {
1380
1381         // insert file functions
1382         case LFUN_LINE_DELETE_FORWARD:
1383                 cur.recordUndoInset();
1384                 //autocorrect_ = false;
1385                 //macroModeClose();
1386                 //if (selection_) {
1387                 //      selDel();
1388                 //      break;
1389                 //}
1390                 if (nrows() > 1)
1391                         delRow(cur.row());
1392                 if (cur.idx() > cur.lastidx())
1393                         cur.idx() = cur.lastidx();
1394                 if (cur.pos() > cur.lastpos())
1395                         cur.pos() = cur.lastpos();
1396                 break;
1397
1398         case LFUN_CELL_SPLIT:
1399                 cur.recordUndo();
1400                 splitCell(cur);
1401                 break;
1402
1403         case LFUN_CELL_BACKWARD:
1404                 // See below.
1405                 cur.setSelection(false);
1406                 if (!idxPrev(cur)) {
1407                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1408                         cur.undispatched();
1409                 }
1410                 break;
1411
1412         case LFUN_CELL_FORWARD:
1413                 // Can't handle selection by additional 'shift' as this is
1414                 // hard bound to LFUN_CELL_BACKWARD
1415                 cur.setSelection(false);
1416                 if (!idxNext(cur)) {
1417                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1418                         cur.undispatched();
1419                 }
1420                 break;
1421
1422         case LFUN_NEWLINE_INSERT: {
1423                 cur.recordUndoInset();
1424                 row_type const r = cur.row();
1425                 addRow(r);
1426
1427                 // split line
1428                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1429                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1430
1431                 // split cell
1432                 splitCell(cur);
1433                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1434                 if (cur.idx() > 0)
1435                         --cur.idx();
1436                 cur.pos() = cur.lastpos();
1437                 cur.forceBufferUpdate();
1438                 //mathcursor->normalize();
1439                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1440                 break;
1441         }
1442
1443         case LFUN_INSET_MODIFY: {
1444                 cur.recordUndoInset();
1445                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1446                 istringstream is(to_utf8(cmd.argument()));
1447                 string s;
1448                 is >> s;
1449                 if (s != "tabular") {
1450                         InsetMathNest::doDispatch(cur, cmd);
1451                         return;
1452                 }
1453                 is >> s;
1454                 if (s == "valign-top")
1455                         setVerticalAlignment('t');
1456                 else if (s == "valign-middle")
1457                         setVerticalAlignment('c');
1458                 else if (s == "valign-bottom")
1459                         setVerticalAlignment('b');
1460                 else if (s == "align-left")
1461                         setHorizontalAlignment('l', cur.col());
1462                 else if (s == "align-right")
1463                         setHorizontalAlignment('r', cur.col());
1464                 else if (s == "align-center")
1465                         setHorizontalAlignment('c', cur.col());
1466                 else if (s == "append-row")
1467                         for (int i = 0, n = extractInt(is); i < n; ++i)
1468                                 addRow(cur.row());
1469                 else if (s == "delete-row") {
1470                         cur.clearSelection(); // bug 4323
1471                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1472                                 delRow(cur.row());
1473                                 if (cur.idx() >= nargs())
1474                                         cur.idx() -= ncols();
1475                         }
1476                         cur.pos() = 0; // trick, see below
1477                 }
1478                 else if (s == "copy-row") {
1479                         // Here (as later) we save the cursor col/row
1480                         // in order to restore it after operation.
1481                         row_type const r = cur.row();
1482                         col_type const c = cur.col();
1483                         for (int i = 0, n = extractInt(is); i < n; ++i)
1484                                 copyRow(cur.row());
1485                         cur.idx() = index(r, c);
1486                 }
1487                 else if (s == "swap-row") {
1488                         swapRow(cur.row());
1489                         // Trick to suppress same-idx-means-different-cell
1490                         // assertion crash:
1491                         cur.pos() = 0;
1492                 }
1493                 else if (s == "add-hline-above")
1494                         rowinfo_[cur.row()].lines_++;
1495                 else if (s == "add-hline-below")
1496                         rowinfo_[cur.row()+1].lines_++;
1497                 else if (s == "delete-hline-above")
1498                         rowinfo_[cur.row()].lines_--;
1499                 else if (s == "delete-hline-below")
1500                         rowinfo_[cur.row()+1].lines_--;
1501                 else if (s == "append-column") {
1502                         row_type const r = cur.row();
1503                         col_type const c = cur.col();
1504                         for (int i = 0, n = extractInt(is); i < n; ++i)
1505                                 addCol(cur.col() + 1);
1506                         cur.idx() = index(r, c);
1507                 }
1508                 else if (s == "delete-column") {
1509                         cur.clearSelection(); // bug 4323
1510                         row_type const r = cur.row();
1511                         col_type const c = cur.col();
1512                         for (int i = 0, n = extractInt(is); i < n; ++i)
1513                                 delCol(col(cur.idx()));
1514                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1515                         cur.pos() = 0; // trick, see above
1516                 }
1517                 else if (s == "copy-column") {
1518                         row_type const r = cur.row();
1519                         col_type const c = cur.col();
1520                         copyCol(cur.col());
1521                         cur.idx() = index(r, c);
1522                 }
1523                 else if (s == "swap-column") {
1524                         swapCol(cur.col());
1525                         cur.pos() = 0; // trick, see above
1526                 }
1527                 else if (s == "add-vline-left") {
1528                         colinfo_[cur.col()].lines_++;
1529                         if (!colinfo_[cur.col()].special_.empty())
1530                                 colinfo_[cur.col()].special_ += '|';
1531                 }
1532                 else if (s == "add-vline-right") {
1533                         colinfo_[cur.col()+1].lines_++;
1534                         if (!colinfo_[cur.col()+1].special_.empty())
1535                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1536                 }
1537                 else if (s == "delete-vline-left") {
1538                         colinfo_[cur.col()].lines_--;
1539                         docstring & special = colinfo_[cur.col()].special_;
1540                         if (!special.empty()) {
1541                                 docstring::size_type i = special.rfind('|');
1542                                 LASSERT(i != docstring::npos, break);
1543                                 special.erase(i, 1);
1544                         }
1545                 }
1546                 else if (s == "delete-vline-right") {
1547                         colinfo_[cur.col()+1].lines_--;
1548                         docstring & special = colinfo_[cur.col()+1].special_;
1549                         if (!special.empty()) {
1550                                 docstring::size_type i = special.find('|');
1551                                 LASSERT(i != docstring::npos, break);
1552                                 special.erase(i, 1);
1553                         }
1554                 }
1555                 else {
1556                         cur.undispatched();
1557                         break;
1558                 }
1559                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1560                 //lyxerr << "returning FINISHED_LEFT" << endl;
1561                 break;
1562         }
1563
1564         case LFUN_CLIPBOARD_PASTE:
1565                 parseflg |= Parse::VERBATIM;
1566                 // fall through
1567         case LFUN_PASTE: {
1568                 if (cur.currentMode() <= TEXT_MODE)
1569                         parseflg |= Parse::TEXTMODE;
1570                 cur.message(_("Paste"));
1571                 cap::replaceSelection(cur);
1572                 docstring topaste;
1573                 if (cmd.argument().empty() && !theClipboard().isInternal())
1574                         topaste = theClipboard().getAsText(Clipboard::PlainTextType);
1575                 else {
1576                         idocstringstream is(cmd.argument());
1577                         int n = 0;
1578                         is >> n;
1579                         topaste = cap::selection(n, buffer().params().documentClassPtr());
1580                 }
1581                 InsetMathGrid grid(buffer_, 1, 1);
1582                 if (!topaste.empty())
1583                         if ((topaste.size() == 1 && isAscii(topaste))
1584                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1585                                 resetGrid(grid);
1586                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1587                         }
1588
1589                 bool hline_enabled = false;
1590                 FuncRequest fr = FuncRequest(LFUN_INSET_MODIFY, "tabular add-hline-above");
1591                 FuncStatus status;
1592                 if (getStatus(cur, fr, status))
1593                         hline_enabled = status.enabled();
1594                 if (grid.nargs() == 1) {
1595                         // single cell/part of cell
1596                         cur.recordUndoInset();
1597                         cur.cell().insert(cur.pos(), grid.cell(0));
1598                         cur.pos() += grid.cell(0).size();
1599                         if (hline_enabled)
1600                                 rowinfo_[cur.row()].lines_ += grid.rowinfo_[0].lines_;
1601                         else {
1602                                 for (unsigned int l = 0; l < grid.rowinfo_[0].lines_; ++l) {
1603                                          cur.cell().insert(0,
1604                                                 MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1605                                          cur.pos()++;
1606                                 }
1607                         }
1608                 } else {
1609                         // multiple cells
1610                         cur.recordUndoInset();
1611                         col_type const numcols =
1612                                 min(grid.ncols(), ncols() - col(cur.idx()));
1613                         row_type const numrows =
1614                                 min(grid.nrows(), nrows() - cur.row());
1615                         for (row_type r = 0; r < numrows; ++r) {
1616                                 for (col_type c = 0; c < numcols; ++c) {
1617                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1618                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1619                                 }
1620                                 if (hline_enabled)
1621                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1622                                 else {
1623                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1624                                                 idx_type i = index(r + cur.row(), 0);
1625                                                 cell(i).insert(0,
1626                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1627                                         }
1628                                 }
1629                                 // append the left over horizontal cells to the last column
1630                                 idx_type i = index(r + cur.row(), ncols() - 1);
1631                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1632                                         cell(i).append(grid.cell(grid.index(r, c)));
1633                         }
1634                         // append the left over vertical cells to the last _cell_
1635                         idx_type i = nargs() - 1;
1636                         for (row_type r = numrows; r < grid.nrows(); ++r) {
1637                                 for (col_type c = 0; c < grid.ncols(); ++c)
1638                                         cell(i).append(grid.cell(grid.index(r, c)));
1639                                 if (hline_enabled)
1640                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1641                                 else {
1642                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1643                                                 cell(i).insert(0,
1644                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1645                                         }
1646                                 }
1647                         }
1648                 }
1649                 cur.clearSelection(); // bug 393
1650                 // FIXME audit setBuffer calls
1651                 cur.inset().setBuffer(*buffer_);
1652                 cur.forceBufferUpdate();
1653                 cur.finishUndo();
1654                 break;
1655         }
1656
1657         case LFUN_LINE_BEGIN:
1658         case LFUN_WORD_BACKWARD:
1659         case LFUN_WORD_LEFT:
1660                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1661                 // fall through
1662         case LFUN_LINE_BEGIN_SELECT:
1663         case LFUN_WORD_BACKWARD_SELECT:
1664         case LFUN_WORD_LEFT_SELECT:
1665                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1666                                 act == LFUN_WORD_LEFT_SELECT ||
1667                                 act == LFUN_LINE_BEGIN_SELECT);
1668                 cur.macroModeClose();
1669                 if (cur.pos() != 0) {
1670                         cur.pos() = 0;
1671                 } else if (cur.idx() % cur.ncols() != 0) {
1672                         cur.idx() -= cur.idx() % cur.ncols();
1673                         cur.pos() = 0;
1674                 } else if (cur.idx() != 0) {
1675                         cur.idx() = 0;
1676                         cur.pos() = 0;
1677                 } else {
1678                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1679                         cur.undispatched();
1680                 }
1681                 break;
1682
1683         case LFUN_WORD_FORWARD:
1684         case LFUN_WORD_RIGHT:
1685         case LFUN_LINE_END:
1686                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1687                 // fall through
1688         case LFUN_WORD_FORWARD_SELECT:
1689         case LFUN_WORD_RIGHT_SELECT:
1690         case LFUN_LINE_END_SELECT:
1691                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1692                                 act == LFUN_WORD_RIGHT_SELECT ||
1693                                 act == LFUN_LINE_END_SELECT);
1694                 cur.macroModeClose();
1695                 cur.clearTargetX();
1696                 if (cur.pos() != cur.lastpos()) {
1697                         cur.pos() = cur.lastpos();
1698                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1699                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1700                         cur.pos() = cur.lastpos();
1701                 } else if (cur.idx() != cur.lastidx()) {
1702                         cur.idx() = cur.lastidx();
1703                         cur.pos() = cur.lastpos();
1704                 } else {
1705                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1706                         cur.undispatched();
1707                 }
1708                 break;
1709
1710         default:
1711                 InsetMathNest::doDispatch(cur, cmd);
1712         }
1713 }
1714
1715
1716 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1717                 FuncStatus & status) const
1718 {
1719         switch (cmd.action()) {
1720         case LFUN_INSET_MODIFY: {
1721                 istringstream is(to_utf8(cmd.argument()));
1722                 string s;
1723                 is >> s;
1724                 if (s != "tabular") {
1725                         // We only now about table actions here.
1726                         break;
1727                 }
1728                 if (&cur.inset() != this) {
1729                         // Table actions requires that the cursor is _inside_ the
1730                         // table.
1731                         status.setEnabled(false);
1732                         status.message(from_utf8(N_("Cursor not in table")));
1733                         return true;
1734                 }
1735                 is >> s;
1736                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1737                         status.setEnabled(false);
1738                         status.message(from_utf8(N_("Only one row")));
1739                         return true;
1740                 }
1741                 if (ncols() <= 1 &&
1742                     (s == "delete-column" || s == "swap-column")) {
1743                         status.setEnabled(false);
1744                         status.message(from_utf8(N_("Only one column")));
1745                         return true;
1746                 }
1747                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1748                      s == "delete-hline-above") ||
1749                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1750                      s == "delete-hline-below")) {
1751                         status.setEnabled(false);
1752                         status.message(from_utf8(N_("No hline to delete")));
1753                         return true;
1754                 }
1755
1756                 if ((colinfo_[cur.col()].lines_ == 0 &&
1757                      s == "delete-vline-left") ||
1758                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1759                      s == "delete-vline-right")) {
1760                         status.setEnabled(false);
1761                         status.message(from_utf8(N_("No vline to delete")));
1762                         return true;
1763                 }
1764                 if (s == "valign-top" || s == "valign-middle" ||
1765                     s == "valign-bottom" || s == "align-left" ||
1766                     s == "align-right" || s == "align-center") {
1767                         status.setEnabled(true);
1768                         char const ha = horizontalAlignment(cur.col());
1769                         char const va = verticalAlignment();
1770                         status.setOnOff((s == "align-left" && ha == 'l')
1771                                         || (s == "align-right"   && ha == 'r')
1772                                         || (s == "align-center"  && ha == 'c')
1773                                         || (s == "valign-top"    && va == 't')
1774                                         || (s == "valign-bottom" && va == 'b')
1775                                         || (s == "valign-middle" && va == 'c'));
1776                         return true;
1777                 }
1778                 if (s == "append-row" || s == "delete-row" ||
1779                     s == "copy-row" || s == "swap-row" ||
1780                     s == "add-hline-above" || s == "add-hline-below" ||
1781                     s == "delete-hline-above" || s == "delete-hline-below" ||
1782                     s == "append-column" || s == "delete-column" ||
1783                     s == "copy-column" || s == "swap-column" ||
1784                     s == "add-vline-left" || s == "add-vline-right" ||
1785                     s == "delete-vline-left" || s == "delete-vline-right") {
1786                         status.setEnabled(true);
1787                 } else {
1788                         status.setEnabled(false);
1789                         status.message(bformat(
1790                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1791                 }
1792
1793 #if 0
1794                 // FIXME: What did this code do?
1795                 // Please check whether it is still needed!
1796                 // should be more precise
1797                 if (v_align_ == '\0') {
1798                         status.enable(true);
1799                         break;
1800                 }
1801                 if (cmd.argument().empty()) {
1802                         status.enable(false);
1803                         break;
1804                 }
1805                 if (!contains("tcb", cmd.argument()[0])) {
1806                         status.enable(false);
1807                         break;
1808                 }
1809                 status.setOnOff(cmd.argument()[0] == v_align_);
1810                 status.setEnabled(true);
1811 #endif
1812                 return true;
1813         }
1814
1815         case LFUN_CELL_SPLIT:
1816                 status.setEnabled(cur.idx() != cur.lastidx());
1817                 return true;
1818
1819         case LFUN_CELL_BACKWARD:
1820         case LFUN_CELL_FORWARD:
1821                 status.setEnabled(true);
1822                 return true;
1823
1824         default:
1825                 break;
1826         }
1827         return InsetMathNest::getStatus(cur, cmd, status);
1828 }
1829
1830
1831 } // namespace lyx