]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
ae325583617d165e3c4cf4181b91a353a6ec5759
[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                         if (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN)
1260                                 continue;
1261                         bool const empty_cell = cell(idx).empty();
1262                         if (!empty_cell)
1263                                 last_eoln = false;
1264                         if (!empty_cell || colinfo_[col + 1].lines_) {
1265                                 lastcol = col + 1;
1266                                 emptyline = false;
1267                         }
1268                 }
1269                 for (col_type col = beg_col; col < lastcol;) {
1270                         int nccols = 1;
1271                         idx_type const idx = index(row, col);
1272                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1273                                 size_t s = col + 1;
1274                                 while (s < ncols() &&
1275                                        cellinfo_[index(row, s)].multi_ == CELL_PART_OF_MULTICOLUMN)
1276                                         s++;
1277                                 nccols = s - col;
1278                                 os << "\\multicolumn{" << nccols
1279                                    << "}{" << cellinfo_[idx].align_
1280                                    << "}{";
1281                         }
1282                         os << cell(idx);
1283                         if (os.pendingBrace())
1284                                 ModeSpecifier specifier(os, TEXT_MODE);
1285                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1286                                 os << '}';
1287                         os << eocString(col, lastcol);
1288                         col += nccols;
1289                 }
1290                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1291                 os << eol;
1292                 // append newline only if line wasn't completely empty
1293                 // and the formula is not written on a single line
1294                 bool const empty = emptyline && eol.empty();
1295                 if (!empty && nrows() > 1)
1296                         os << "\n";
1297         }
1298         // @TODO use end_row instead of nrows() ?
1299         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1300         if (!s.empty()) {
1301                 if (eol.empty()) {
1302                         if (os.fragile())
1303                                 os << "\\protect";
1304                         os << "\\\\";
1305                 }
1306                 os << s;
1307         }
1308 }
1309
1310
1311 int InsetMathGrid::colsep() const
1312 {
1313         return 6;
1314 }
1315
1316
1317 int InsetMathGrid::rowsep() const
1318 {
1319         return 6;
1320 }
1321
1322
1323 int InsetMathGrid::hlinesep() const
1324 {
1325         return 3;
1326 }
1327
1328
1329 int InsetMathGrid::vlinesep() const
1330 {
1331         return 3;
1332 }
1333
1334
1335 int InsetMathGrid::border() const
1336 {
1337         return 1;
1338 }
1339
1340
1341 void InsetMathGrid::splitCell(Cursor & cur)
1342 {
1343         if (cur.idx() == cur.lastidx())
1344                 return;
1345         MathData ar = cur.cell();
1346         ar.erase(0, cur.pos());
1347         cur.cell().erase(cur.pos(), cur.lastpos());
1348         ++cur.idx();
1349         while (cur.idx() << nargs() &&
1350                cellinfo_[cur.idx()].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1351                 ++cur.idx();
1352         cur.pos() = 0;
1353         cur.cell().insert(0, ar);
1354 }
1355
1356
1357 char InsetMathGrid::displayColAlign(idx_type idx) const
1358 {
1359         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1360                 // align_ may also contain lines like "||r|", so this is
1361                 // not complete, but we catch at least the simple cases.
1362                 if (cellinfo_[idx].align_ == "c")
1363                         return 'c';
1364                 if (cellinfo_[idx].align_ == "l")
1365                         return 'l';
1366                 if (cellinfo_[idx].align_ == "r")
1367                         return 'r';
1368         }
1369         return colinfo_[col(idx)].align_;
1370 }
1371
1372
1373 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1374 {
1375         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1376
1377         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1378
1379         FuncCode const act = cmd.action();
1380         switch (act) {
1381
1382         // insert file functions
1383         case LFUN_LINE_DELETE_FORWARD:
1384                 cur.recordUndoInset();
1385                 //autocorrect_ = false;
1386                 //macroModeClose();
1387                 //if (selection_) {
1388                 //      selDel();
1389                 //      break;
1390                 //}
1391                 if (nrows() > 1)
1392                         delRow(cur.row());
1393                 if (cur.idx() > cur.lastidx())
1394                         cur.idx() = cur.lastidx();
1395                 if (cur.pos() > cur.lastpos())
1396                         cur.pos() = cur.lastpos();
1397                 break;
1398
1399         case LFUN_CELL_SPLIT:
1400                 cur.recordUndo();
1401                 splitCell(cur);
1402                 break;
1403
1404         case LFUN_CELL_BACKWARD:
1405                 // See below.
1406                 cur.setSelection(false);
1407                 if (!idxPrev(cur)) {
1408                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1409                         cur.undispatched();
1410                 }
1411                 break;
1412
1413         case LFUN_CELL_FORWARD:
1414                 // Can't handle selection by additional 'shift' as this is
1415                 // hard bound to LFUN_CELL_BACKWARD
1416                 cur.setSelection(false);
1417                 if (!idxNext(cur)) {
1418                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1419                         cur.undispatched();
1420                 }
1421                 break;
1422
1423         case LFUN_NEWLINE_INSERT: {
1424                 cur.recordUndoInset();
1425                 row_type const r = cur.row();
1426                 addRow(r);
1427
1428                 // split line
1429                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1430                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1431
1432                 // split cell
1433                 splitCell(cur);
1434                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1435                 if (cur.idx() > 0)
1436                         --cur.idx();
1437                 cur.pos() = cur.lastpos();
1438                 cur.forceBufferUpdate();
1439                 //mathcursor->normalize();
1440                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1441                 break;
1442         }
1443
1444         case LFUN_INSET_MODIFY: {
1445                 cur.recordUndoInset();
1446                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1447                 istringstream is(to_utf8(cmd.argument()));
1448                 string s;
1449                 is >> s;
1450                 if (s != "tabular") {
1451                         InsetMathNest::doDispatch(cur, cmd);
1452                         return;
1453                 }
1454                 is >> s;
1455                 if (s == "valign-top")
1456                         setVerticalAlignment('t');
1457                 else if (s == "valign-middle")
1458                         setVerticalAlignment('c');
1459                 else if (s == "valign-bottom")
1460                         setVerticalAlignment('b');
1461                 else if (s == "align-left")
1462                         setHorizontalAlignment('l', cur.col());
1463                 else if (s == "align-right")
1464                         setHorizontalAlignment('r', cur.col());
1465                 else if (s == "align-center")
1466                         setHorizontalAlignment('c', cur.col());
1467                 else if (s == "append-row")
1468                         for (int i = 0, n = extractInt(is); i < n; ++i)
1469                                 addRow(cur.row());
1470                 else if (s == "delete-row") {
1471                         cur.clearSelection(); // bug 4323
1472                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1473                                 delRow(cur.row());
1474                                 if (cur.idx() >= nargs())
1475                                         cur.idx() -= ncols();
1476                         }
1477                         cur.pos() = 0; // trick, see below
1478                 }
1479                 else if (s == "copy-row") {
1480                         // Here (as later) we save the cursor col/row
1481                         // in order to restore it after operation.
1482                         row_type const r = cur.row();
1483                         col_type const c = cur.col();
1484                         for (int i = 0, n = extractInt(is); i < n; ++i)
1485                                 copyRow(cur.row());
1486                         cur.idx() = index(r, c);
1487                 }
1488                 else if (s == "swap-row") {
1489                         swapRow(cur.row());
1490                         // Trick to suppress same-idx-means-different-cell
1491                         // assertion crash:
1492                         cur.pos() = 0;
1493                 }
1494                 else if (s == "add-hline-above")
1495                         rowinfo_[cur.row()].lines_++;
1496                 else if (s == "add-hline-below")
1497                         rowinfo_[cur.row()+1].lines_++;
1498                 else if (s == "delete-hline-above")
1499                         rowinfo_[cur.row()].lines_--;
1500                 else if (s == "delete-hline-below")
1501                         rowinfo_[cur.row()+1].lines_--;
1502                 else if (s == "append-column") {
1503                         row_type const r = cur.row();
1504                         col_type const c = cur.col();
1505                         for (int i = 0, n = extractInt(is); i < n; ++i)
1506                                 addCol(cur.col() + 1);
1507                         cur.idx() = index(r, c);
1508                 }
1509                 else if (s == "delete-column") {
1510                         cur.clearSelection(); // bug 4323
1511                         row_type const r = cur.row();
1512                         col_type const c = cur.col();
1513                         for (int i = 0, n = extractInt(is); i < n; ++i)
1514                                 delCol(col(cur.idx()));
1515                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1516                         cur.pos() = 0; // trick, see above
1517                 }
1518                 else if (s == "copy-column") {
1519                         row_type const r = cur.row();
1520                         col_type const c = cur.col();
1521                         copyCol(cur.col());
1522                         cur.idx() = index(r, c);
1523                 }
1524                 else if (s == "swap-column") {
1525                         swapCol(cur.col());
1526                         cur.pos() = 0; // trick, see above
1527                 }
1528                 else if (s == "add-vline-left") {
1529                         colinfo_[cur.col()].lines_++;
1530                         if (!colinfo_[cur.col()].special_.empty())
1531                                 colinfo_[cur.col()].special_ += '|';
1532                 }
1533                 else if (s == "add-vline-right") {
1534                         colinfo_[cur.col()+1].lines_++;
1535                         if (!colinfo_[cur.col()+1].special_.empty())
1536                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1537                 }
1538                 else if (s == "delete-vline-left") {
1539                         colinfo_[cur.col()].lines_--;
1540                         docstring & special = colinfo_[cur.col()].special_;
1541                         if (!special.empty()) {
1542                                 docstring::size_type i = special.rfind('|');
1543                                 LASSERT(i != docstring::npos, break);
1544                                 special.erase(i, 1);
1545                         }
1546                 }
1547                 else if (s == "delete-vline-right") {
1548                         colinfo_[cur.col()+1].lines_--;
1549                         docstring & special = colinfo_[cur.col()+1].special_;
1550                         if (!special.empty()) {
1551                                 docstring::size_type i = special.find('|');
1552                                 LASSERT(i != docstring::npos, break);
1553                                 special.erase(i, 1);
1554                         }
1555                 }
1556                 else {
1557                         cur.undispatched();
1558                         break;
1559                 }
1560                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1561                 //lyxerr << "returning FINISHED_LEFT" << endl;
1562                 break;
1563         }
1564
1565         case LFUN_CLIPBOARD_PASTE:
1566                 parseflg |= Parse::VERBATIM;
1567                 // fall through
1568         case LFUN_PASTE: {
1569                 if (cur.currentMode() <= TEXT_MODE)
1570                         parseflg |= Parse::TEXTMODE;
1571                 cur.message(_("Paste"));
1572                 cap::replaceSelection(cur);
1573                 docstring topaste;
1574                 if (cmd.argument().empty() && !theClipboard().isInternal())
1575                         topaste = theClipboard().getAsText(Clipboard::PlainTextType);
1576                 else {
1577                         idocstringstream is(cmd.argument());
1578                         int n = 0;
1579                         is >> n;
1580                         topaste = cap::selection(n, buffer().params().documentClassPtr());
1581                 }
1582                 InsetMathGrid grid(buffer_, 1, 1);
1583                 if (!topaste.empty())
1584                         if ((topaste.size() == 1 && isAscii(topaste))
1585                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1586                                 resetGrid(grid);
1587                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1588                         }
1589
1590                 bool hline_enabled = false;
1591                 FuncRequest fr = FuncRequest(LFUN_INSET_MODIFY, "tabular add-hline-above");
1592                 FuncStatus status;
1593                 if (getStatus(cur, fr, status))
1594                         hline_enabled = status.enabled();
1595                 if (grid.nargs() == 1) {
1596                         // single cell/part of cell
1597                         cur.recordUndoInset();
1598                         cur.cell().insert(cur.pos(), grid.cell(0));
1599                         cur.pos() += grid.cell(0).size();
1600                         if (hline_enabled)
1601                                 rowinfo_[cur.row()].lines_ += grid.rowinfo_[0].lines_;
1602                         else {
1603                                 for (unsigned int l = 0; l < grid.rowinfo_[0].lines_; ++l) {
1604                                          cur.cell().insert(0,
1605                                                 MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1606                                          cur.pos()++;
1607                                 }
1608                         }
1609                 } else {
1610                         // multiple cells
1611                         cur.recordUndoInset();
1612                         col_type const numcols =
1613                                 min(grid.ncols(), ncols() - col(cur.idx()));
1614                         row_type const numrows =
1615                                 min(grid.nrows(), nrows() - cur.row());
1616                         for (row_type r = 0; r < numrows; ++r) {
1617                                 for (col_type c = 0; c < numcols; ++c) {
1618                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1619                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1620                                 }
1621                                 if (hline_enabled)
1622                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1623                                 else {
1624                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1625                                                 idx_type i = index(r + cur.row(), 0);
1626                                                 cell(i).insert(0,
1627                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1628                                         }
1629                                 }
1630                                 // append the left over horizontal cells to the last column
1631                                 idx_type i = index(r + cur.row(), ncols() - 1);
1632                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1633                                         cell(i).append(grid.cell(grid.index(r, c)));
1634                         }
1635                         // append the left over vertical cells to the last _cell_
1636                         idx_type i = nargs() - 1;
1637                         for (row_type r = numrows; r < grid.nrows(); ++r) {
1638                                 for (col_type c = 0; c < grid.ncols(); ++c)
1639                                         cell(i).append(grid.cell(grid.index(r, c)));
1640                                 if (hline_enabled)
1641                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1642                                 else {
1643                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1644                                                 cell(i).insert(0,
1645                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1646                                         }
1647                                 }
1648                         }
1649                 }
1650                 cur.clearSelection(); // bug 393
1651                 // FIXME audit setBuffer calls
1652                 cur.inset().setBuffer(*buffer_);
1653                 cur.forceBufferUpdate();
1654                 cur.finishUndo();
1655                 break;
1656         }
1657
1658         case LFUN_LINE_BEGIN:
1659         case LFUN_WORD_BACKWARD:
1660         case LFUN_WORD_LEFT:
1661                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1662                 // fall through
1663         case LFUN_LINE_BEGIN_SELECT:
1664         case LFUN_WORD_BACKWARD_SELECT:
1665         case LFUN_WORD_LEFT_SELECT:
1666                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1667                                 act == LFUN_WORD_LEFT_SELECT ||
1668                                 act == LFUN_LINE_BEGIN_SELECT);
1669                 cur.macroModeClose();
1670                 if (cur.pos() != 0) {
1671                         cur.pos() = 0;
1672                 } else if (cur.idx() % cur.ncols() != 0) {
1673                         cur.idx() -= cur.idx() % cur.ncols();
1674                         cur.pos() = 0;
1675                 } else if (cur.idx() != 0) {
1676                         cur.idx() = 0;
1677                         cur.pos() = 0;
1678                 } else {
1679                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1680                         cur.undispatched();
1681                 }
1682                 break;
1683
1684         case LFUN_WORD_FORWARD:
1685         case LFUN_WORD_RIGHT:
1686         case LFUN_LINE_END:
1687                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1688                 // fall through
1689         case LFUN_WORD_FORWARD_SELECT:
1690         case LFUN_WORD_RIGHT_SELECT:
1691         case LFUN_LINE_END_SELECT:
1692                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1693                                 act == LFUN_WORD_RIGHT_SELECT ||
1694                                 act == LFUN_LINE_END_SELECT);
1695                 cur.macroModeClose();
1696                 cur.clearTargetX();
1697                 if (cur.pos() != cur.lastpos()) {
1698                         cur.pos() = cur.lastpos();
1699                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1700                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1701                         cur.pos() = cur.lastpos();
1702                 } else if (cur.idx() != cur.lastidx()) {
1703                         cur.idx() = cur.lastidx();
1704                         cur.pos() = cur.lastpos();
1705                 } else {
1706                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1707                         cur.undispatched();
1708                 }
1709                 break;
1710
1711         default:
1712                 InsetMathNest::doDispatch(cur, cmd);
1713         }
1714 }
1715
1716
1717 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1718                 FuncStatus & status) const
1719 {
1720         switch (cmd.action()) {
1721         case LFUN_INSET_MODIFY: {
1722                 istringstream is(to_utf8(cmd.argument()));
1723                 string s;
1724                 is >> s;
1725                 if (s != "tabular") {
1726                         // We only now about table actions here.
1727                         break;
1728                 }
1729                 if (&cur.inset() != this) {
1730                         // Table actions requires that the cursor is _inside_ the
1731                         // table.
1732                         status.setEnabled(false);
1733                         status.message(from_utf8(N_("Cursor not in table")));
1734                         return true;
1735                 }
1736                 is >> s;
1737                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1738                         status.setEnabled(false);
1739                         status.message(from_utf8(N_("Only one row")));
1740                         return true;
1741                 }
1742                 if (ncols() <= 1 &&
1743                     (s == "delete-column" || s == "swap-column")) {
1744                         status.setEnabled(false);
1745                         status.message(from_utf8(N_("Only one column")));
1746                         return true;
1747                 }
1748                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1749                      s == "delete-hline-above") ||
1750                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1751                      s == "delete-hline-below")) {
1752                         status.setEnabled(false);
1753                         status.message(from_utf8(N_("No hline to delete")));
1754                         return true;
1755                 }
1756
1757                 if ((colinfo_[cur.col()].lines_ == 0 &&
1758                      s == "delete-vline-left") ||
1759                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1760                      s == "delete-vline-right")) {
1761                         status.setEnabled(false);
1762                         status.message(from_utf8(N_("No vline to delete")));
1763                         return true;
1764                 }
1765                 if (s == "valign-top" || s == "valign-middle" ||
1766                     s == "valign-bottom" || s == "align-left" ||
1767                     s == "align-right" || s == "align-center") {
1768                         status.setEnabled(true);
1769                         char const ha = horizontalAlignment(cur.col());
1770                         char const va = verticalAlignment();
1771                         status.setOnOff((s == "align-left" && ha == 'l')
1772                                         || (s == "align-right"   && ha == 'r')
1773                                         || (s == "align-center"  && ha == 'c')
1774                                         || (s == "valign-top"    && va == 't')
1775                                         || (s == "valign-bottom" && va == 'b')
1776                                         || (s == "valign-middle" && va == 'c'));
1777                         return true;
1778                 }
1779                 if (s == "append-row" || s == "delete-row" ||
1780                     s == "copy-row" || s == "swap-row" ||
1781                     s == "add-hline-above" || s == "add-hline-below" ||
1782                     s == "delete-hline-above" || s == "delete-hline-below" ||
1783                     s == "append-column" || s == "delete-column" ||
1784                     s == "copy-column" || s == "swap-column" ||
1785                     s == "add-vline-left" || s == "add-vline-right" ||
1786                     s == "delete-vline-left" || s == "delete-vline-right") {
1787                         status.setEnabled(true);
1788                 } else {
1789                         status.setEnabled(false);
1790                         status.message(bformat(
1791                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1792                 }
1793
1794 #if 0
1795                 // FIXME: What did this code do?
1796                 // Please check whether it is still needed!
1797                 // should be more precise
1798                 if (v_align_ == '\0') {
1799                         status.enable(true);
1800                         break;
1801                 }
1802                 if (cmd.argument().empty()) {
1803                         status.enable(false);
1804                         break;
1805                 }
1806                 if (!contains("tcb", cmd.argument()[0])) {
1807                         status.enable(false);
1808                         break;
1809                 }
1810                 status.setOnOff(cmd.argument()[0] == v_align_);
1811                 status.setEnabled(true);
1812 #endif
1813                 return true;
1814         }
1815
1816         case LFUN_CELL_SPLIT:
1817                 status.setEnabled(cur.idx() != cur.lastidx());
1818                 return true;
1819
1820         case LFUN_CELL_BACKWARD:
1821         case LFUN_CELL_FORWARD:
1822                 status.setEnabled(true);
1823                 return true;
1824
1825         default:
1826                 break;
1827         }
1828         return InsetMathNest::getStatus(cur, cmd, status);
1829 }
1830
1831
1832 } // namespace lyx