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