]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
58784ad79b5672d641b11cf662a537da1e0627de
[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());
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 }
839
840
841 void InsetMathGrid::swapRow(row_type row)
842 {
843         if (nrows() == 1)
844                 return;
845         if (row + 1 == nrows())
846                 --row;
847         for (col_type col = 0; col < ncols(); ++col)
848                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
849 }
850
851
852 void InsetMathGrid::addCol(col_type newcol)
853 {
854         const col_type nc = ncols();
855         const row_type nr = nrows();
856         cells_type new_cells((nc + 1) * nr);
857         vector<CellInfo> new_cellinfo((nc + 1) * nr);
858
859         for (row_type row = 0; row < nr; ++row)
860                 for (col_type col = 0; col < nc; ++col) {
861                         new_cells[row * (nc + 1) + col + (col >= newcol)]
862                                 = cells_[row * nc + col];
863                         new_cellinfo[row * (nc + 1) + col + (col >= newcol)]
864                                 = cellinfo_[row * nc + col];
865                 }
866         swap(cells_, new_cells);
867         swap(cellinfo_, new_cellinfo);
868
869         ColInfo inf;
870         inf.skip_  = defaultColSpace(newcol);
871         inf.align_ = defaultColAlign(newcol);
872         colinfo_.insert(colinfo_.begin() + newcol, inf);
873 }
874
875
876 void InsetMathGrid::delCol(col_type col)
877 {
878         if (ncols() == 1)
879                 return;
880
881         cells_type tmpcells;
882         vector<CellInfo> tmpcellinfo;
883         for (col_type i = 0; i < nargs(); ++i)
884                 if (i % ncols() != col) {
885                         tmpcells.push_back(cells_[i]);
886                         tmpcellinfo.push_back(cellinfo_[i]);
887                 }
888         swap(cells_, tmpcells);
889         swap(cellinfo_, tmpcellinfo);
890
891         colinfo_.erase(colinfo_.begin() + col);
892 }
893
894
895 void InsetMathGrid::copyCol(col_type col)
896 {
897         addCol(col+1);
898         for (row_type row = 0; row < nrows(); ++row)
899                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
900 }
901
902
903 void InsetMathGrid::swapCol(col_type col)
904 {
905         if (ncols() == 1)
906                 return;
907         if (col + 1 == ncols())
908                 --col;
909         for (row_type row = 0; row < nrows(); ++row)
910                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
911 }
912
913
914 int InsetMathGrid::cellXOffset(BufferView const & bv, idx_type idx) const
915 {
916         if (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN)
917                 return 0;
918         col_type c = col(idx);
919         int x = colinfo_[c].offset_;
920         char align = displayColAlign(idx);
921         Dimension const & celldim = cell(idx).dimension(bv);
922         if (align == 'r' || align == 'R')
923                 x += cellWidth(idx) - celldim.wid;
924         if (align == 'c' || align == 'C')
925                 x += (cellWidth(idx) - celldim.wid) / 2;
926         return x;
927 }
928
929
930 int InsetMathGrid::cellYOffset(idx_type idx) const
931 {
932         return rowinfo_[row(idx)].offset_;
933 }
934
935
936 int InsetMathGrid::cellWidth(idx_type idx) const
937 {
938         switch (cellinfo_[idx].multi_) {
939         case CELL_NORMAL:
940                 return colinfo_[col(idx)].width_;
941         case CELL_BEGIN_OF_MULTICOLUMN: {
942                 col_type c1 = col(idx);
943                 col_type c2 = c1 + ncellcols(idx);
944                 return colinfo_[c2].offset_
945                         - colinfo_[c1].offset_
946                         - displayColSpace(c2)
947                         - colsep()
948                         - colinfo_[c2].lines_ * vlinesep();
949         }
950         case CELL_PART_OF_MULTICOLUMN:
951                 return 0;
952         }
953         return 0;
954 }
955
956
957 bool InsetMathGrid::idxUpDown(Cursor & cur, bool up) const
958 {
959         if (up) {
960                 if (cur.row() == 0)
961                         return false;
962                 cur.idx() -= ncols();
963         } else {
964                 if (cur.row() + 1 >= nrows())
965                         return false;
966                 cur.idx() += ncols();
967         }
968         // If we are in a multicolumn cell, move to the "real" cell
969         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
970                 LASSERT(cur.idx() > 0, return false);
971                 --cur.idx();
972         }
973         // FIXME: this is only a workaround to avoid a crash if the inset
974         // in not in coord cache. The best would be to force a FitCursor
975         // operation.
976         CoordCache::Arrays const & arraysCache = cur.bv().coordCache().arrays();
977         if (arraysCache.has(&cur.cell()))
978                 cur.pos() = cur.cell().x2pos(&cur.bv(), cur.x_target() - cur.cell().xo(cur.bv()));
979         else
980                 cur.pos() = 0;
981         return true;
982 }
983
984
985 bool InsetMathGrid::idxBackward(Cursor & cur) const
986 {
987         // leave matrix if at the front edge
988         if (cur.col() == 0)
989                 return false;
990         --cur.idx();
991         // If we are in a multicolumn cell, move to the "real" cell
992         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
993                 LASSERT(cur.idx() > 0, return false);
994                 --cur.idx();
995         }
996         cur.pos() = cur.lastpos();
997         return true;
998 }
999
1000
1001 bool InsetMathGrid::idxForward(Cursor & cur) const
1002 {
1003         // leave matrix if at the back edge
1004         if (cur.col() + 1 == ncols())
1005                 return false;
1006         ++cur.idx();
1007         // If we are in a multicolumn cell, move to the next cell
1008         while (cellinfo_[cur.idx()].multi_ == CELL_PART_OF_MULTICOLUMN) {
1009                 // leave matrix if at the back edge
1010                 if (cur.col() + 1 == ncols())
1011                         return false;
1012                 ++cur.idx();
1013         }
1014         cur.pos() = 0;
1015         return true;
1016 }
1017
1018
1019 idx_type InsetMathGrid::firstIdx() const
1020 {
1021         size_type idx = 0;
1022         switch (v_align_) {
1023                 case 't':
1024                         //idx = 0;
1025                         break;
1026                 case 'b':
1027                         idx = (nrows() - 1) * ncols();
1028                         break;
1029                 default:
1030                         idx = ((nrows() - 1) / 2) * ncols();
1031         }
1032         // If we are in a multicolumn cell, move to the "real" cell
1033         while (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN) {
1034                 LASSERT(idx > 0, return 0);
1035                 --idx;
1036         }
1037         return idx;
1038 }
1039
1040
1041 idx_type InsetMathGrid::lastIdx() const
1042 {
1043         size_type idx = 0;
1044         switch (v_align_) {
1045                 case 't':
1046                         idx = ncols() - 1;
1047                         break;
1048                 case 'b':
1049                         idx = nargs() - 1;
1050                         break;
1051                 default:
1052                         idx = ((nrows() - 1) / 2 + 1) * ncols() - 1;
1053         }
1054         // If we are in a multicolumn cell, move to the "real" cell
1055         while (cellinfo_[idx].multi_ == CELL_PART_OF_MULTICOLUMN) {
1056                 LASSERT(idx > 0, return false);
1057                 --idx;
1058         }
1059         return idx;
1060 }
1061
1062
1063 bool InsetMathGrid::idxDelete(idx_type & idx)
1064 {
1065         // nothing to do if we have just one row
1066         if (nrows() == 1)
1067                 return false;
1068
1069         // nothing to do if we are in the middle of the last row of the inset
1070         if (idx + ncols() > nargs())
1071                 return false;
1072
1073         // try to delete entire sequence of ncols() empty cells if possible
1074         for (idx_type i = idx; i < idx + ncols(); ++i)
1075                 if (!cell(i).empty())
1076                         return false;
1077
1078         // move cells if necessary
1079         for (idx_type i = index(row(idx), 0); i < idx; ++i)
1080                 swap(cell(i), cell(i + ncols()));
1081
1082         delRow(row(idx));
1083
1084         if (idx >= nargs())
1085                 idx = nargs() - 1;
1086
1087         // undo effect of Ctrl-Tab (i.e. pull next cell)
1088         //if (idx + 1 != nargs())
1089         //      cell(idx).swap(cell(idx + 1));
1090
1091         // we handled the event..
1092         return true;
1093 }
1094
1095
1096 // reimplement old behaviour when pressing Delete in the last position
1097 // of a cell
1098 void InsetMathGrid::idxGlue(idx_type idx)
1099 {
1100         col_type c = col(idx);
1101         if (c + 1 == ncols()) {
1102                 if (row(idx) + 1 != nrows()) {
1103                         for (col_type cc = 0; cc < ncols(); ++cc)
1104                                 cell(idx).append(cell(idx + cc + 1));
1105                         delRow(row(idx) + 1);
1106                 }
1107         } else {
1108                 idx_type idx_next = idx + 1;
1109                 while (idx_next < nargs() &&
1110                        cellinfo_[idx_next].multi_ == CELL_PART_OF_MULTICOLUMN)
1111                         ++idx_next;
1112                 if (idx_next < nargs())
1113                         cell(idx).append(cell(idx_next));
1114                 col_type oldcol = c + 1;
1115                 for (col_type cc = c + 2; cc < ncols(); ++cc)
1116                         cell(idx - oldcol + cc) = cell(idx - oldcol + 1 + cc);
1117                 cell(idx - c + ncols() - 1).clear();
1118         }
1119 }
1120
1121
1122 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
1123 {
1124         return rowinfo_[row];
1125 }
1126
1127
1128 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
1129 {
1130         return rowinfo_[row];
1131 }
1132
1133
1134 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
1135 {
1136         row_type const ri = row(idx);
1137         row_type const r1 = min(row(from), row(to));
1138         row_type const r2 = max(row(from), row(to));
1139         col_type const ci = col(idx);
1140         col_type const c1 = min(col(from), col(to));
1141         col_type const c2 = max(col(from), col(to));
1142         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
1143 }
1144
1145
1146 void InsetMathGrid::normalize(NormalStream & os) const
1147 {
1148         os << "[grid ";
1149         for (row_type row = 0; row < nrows(); ++row) {
1150                 os << "[row ";
1151                 for (col_type col = 0; col < ncols(); ++col) {
1152                         idx_type const i = index(row, col);
1153                         switch (cellinfo_[i].multi_) {
1154                         case CELL_NORMAL:
1155                                 os << "[cell " << cell(i) << ']';
1156                                 break;
1157                         case CELL_BEGIN_OF_MULTICOLUMN:
1158                                 os << "[cell colspan="
1159                                    << static_cast<int>(ncellcols(i)) << ' '
1160                                    << cell(i) << ']';
1161                                 break;
1162                         case CELL_PART_OF_MULTICOLUMN:
1163                                 break;
1164                         }
1165                 }
1166                 os << ']';
1167         }
1168         os << ']';
1169 }
1170
1171
1172 void InsetMathGrid::mathmlize(MathStream & os) const
1173 {
1174         bool const havetable = nrows() > 1 || ncols() > 1;
1175         if (havetable)
1176                 os << MTag("mtable");
1177         char const * const celltag = havetable ? "mtd" : "mrow";
1178         for (row_type row = 0; row < nrows(); ++row) {
1179                 if (havetable)
1180                         os << MTag("mtr");
1181                 for (col_type col = 0; col < ncols(); ++col) {
1182                         idx_type const i = index(row, col);
1183                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1184                                 col_type const cellcols = ncellcols(i);
1185                                 ostringstream attr;
1186                                 if (havetable && cellcols > 1)
1187                                         attr << "colspan='" << cellcols << '\'';
1188                                 os << MTag(celltag, attr.str());
1189                                 os << cell(index(row, col));
1190                                 os << ETag(celltag);
1191                         }
1192                 }
1193                 if (havetable)
1194                         os << ETag("mtr");
1195         }
1196         if (havetable)
1197                 os << ETag("mtable");
1198 }
1199
1200
1201 // FIXME XHTML
1202 // We need to do something about alignment here.
1203 void InsetMathGrid::htmlize(HtmlStream & os, string attrib) const
1204 {
1205         bool const havetable = nrows() > 1 || ncols() > 1;
1206         if (!havetable) {
1207                 os << cell(index(0, 0));
1208                 return;
1209         }
1210         os << MTag("table", attrib);
1211         for (row_type row = 0; row < nrows(); ++row) {
1212                 os << MTag("tr");
1213                 for (col_type col = 0; col < ncols(); ++col) {
1214                         idx_type const i = index(row, col);
1215                         if (cellinfo_[i].multi_ != CELL_PART_OF_MULTICOLUMN) {
1216                                 col_type const cellcols = ncellcols(i);
1217                                 ostringstream attr;
1218                                 if (cellcols > 1)
1219                                         attr << "colspan='" << cellcols << '\'';
1220                                 os << MTag("td", attr.str());
1221                                 os << cell(index(row, col));
1222                                 os << ETag("td");
1223                         }
1224                 }
1225                 os << ETag("tr");
1226         }
1227         os << ETag("table");
1228 }
1229
1230
1231 void InsetMathGrid::htmlize(HtmlStream & os) const
1232 {
1233         htmlize(os, "class='mathtable'");
1234 }
1235
1236
1237 void InsetMathGrid::validate(LaTeXFeatures & features) const
1238 {
1239         if (features.runparams().math_flavor == OutputParams::MathAsHTML
1240             && (nrows() > 1 || ncols() > 1)) {
1241                 // CSS taken from InsetMathCases
1242                 features.addCSSSnippet(
1243                         "table.mathtable{display: inline-block; text-align: center; border: none;"
1244                         "border-left: thin solid black; vertical-align: middle; padding-left: 0.5ex;}\n"
1245                         "table.mathtable td {text-align: left; border: none;}");
1246         }
1247         InsetMathNest::validate(features);
1248 }
1249
1250
1251 void InsetMathGrid::write(WriteStream & os) const
1252 {
1253         write(os, 0, 0, nrows(), ncols());
1254 }
1255
1256 void InsetMathGrid::write(WriteStream & os,
1257                           row_type beg_row, col_type beg_col,
1258                           row_type end_row, col_type end_col) const
1259 {
1260         MathEnsurer ensurer(os, false);
1261         docstring eol;
1262         for (row_type row = beg_row; row < end_row; ++row) {
1263                 os << verboseHLine(rowinfo_[row].lines_);
1264                 // don't write & and empty cells at end of line,
1265                 // unless there are vertical lines
1266                 col_type lastcol = 0;
1267                 bool emptyline = true;
1268                 bool last_eoln = true;
1269                 for (col_type col = beg_col; col < end_col; ++col) {
1270                         idx_type const idx = index(row, col);
1271                         bool const empty_cell = cell(idx).empty();
1272                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL)
1273                                 last_eoln = false;
1274                         if (!empty_cell || cellinfo_[idx].multi_ != CELL_NORMAL ||
1275                             colinfo_[col + 1].lines_) {
1276                                 lastcol = col + 1;
1277                                 emptyline = false;
1278                         }
1279                 }
1280                 for (col_type col = beg_col; col < end_col;) {
1281                         int nccols = 1;
1282                         idx_type const idx = index(row, col);
1283                         TexRow::RowEntry entry = TexRow::mathEntry(id(),idx);
1284                         os.texrow().start(entry);
1285                         if (col >= lastcol) {
1286                                 ++col;
1287                                 continue;
1288                         }
1289                         Changer dummy = os.changeRowEntry(entry);
1290                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1291                                 size_t s = col + 1;
1292                                 while (s < ncols() &&
1293                                        cellinfo_[index(row, s)].multi_ == CELL_PART_OF_MULTICOLUMN)
1294                                         s++;
1295                                 nccols = s - col;
1296                                 os << "\\multicolumn{" << nccols
1297                                    << "}{" << cellinfo_[idx].align_
1298                                    << "}{";
1299                         }
1300                         os << cell(idx);
1301                         if (os.pendingBrace())
1302                                 ModeSpecifier specifier(os, TEXT_MODE);
1303                         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1304                                 os << '}';
1305                         os << eocString(col + nccols - 1, lastcol);
1306                         col += nccols;
1307                 }
1308                 eol = eolString(row, os.fragile(), os.latex(), last_eoln);
1309                 os << eol;
1310                 // append newline only if line wasn't completely empty
1311                 // and the formula is not written on a single line
1312                 bool const empty = emptyline && eol.empty();
1313                 if (!empty && nrows() > 1)
1314                         os << "\n";
1315         }
1316         // @TODO use end_row instead of nrows() ?
1317         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
1318         if (!s.empty()) {
1319                 if (eol.empty()) {
1320                         if (os.fragile())
1321                                 os << "\\protect";
1322                         os << "\\\\";
1323                 }
1324                 os << s;
1325         }
1326 }
1327
1328
1329 int InsetMathGrid::colsep() const
1330 {
1331         return 6;
1332 }
1333
1334
1335 int InsetMathGrid::rowsep() const
1336 {
1337         return 6;
1338 }
1339
1340
1341 int InsetMathGrid::hlinesep() const
1342 {
1343         return 3;
1344 }
1345
1346
1347 int InsetMathGrid::vlinesep() const
1348 {
1349         return 3;
1350 }
1351
1352
1353 int InsetMathGrid::border() const
1354 {
1355         return 1;
1356 }
1357
1358
1359 void InsetMathGrid::splitCell(Cursor & cur)
1360 {
1361         if (cur.idx() == cur.lastidx())
1362                 return;
1363         MathData ar = cur.cell();
1364         ar.erase(0, cur.pos());
1365         cur.cell().erase(cur.pos(), cur.lastpos());
1366         ++cur.idx();
1367         while (cur.idx() << nargs() &&
1368                cellinfo_[cur.idx()].multi_ == CELL_BEGIN_OF_MULTICOLUMN)
1369                 ++cur.idx();
1370         cur.pos() = 0;
1371         cur.cell().insert(0, ar);
1372 }
1373
1374
1375 char InsetMathGrid::displayColAlign(idx_type idx) const
1376 {
1377         if (cellinfo_[idx].multi_ == CELL_BEGIN_OF_MULTICOLUMN) {
1378                 // align_ may also contain lines like "||r|", so this is
1379                 // not complete, but we catch at least the simple cases.
1380                 if (cellinfo_[idx].align_ == "c")
1381                         return 'c';
1382                 if (cellinfo_[idx].align_ == "l")
1383                         return 'l';
1384                 if (cellinfo_[idx].align_ == "r")
1385                         return 'r';
1386         }
1387         return colinfo_[col(idx)].align_;
1388 }
1389
1390
1391 int InsetMathGrid::displayColSpace(col_type col) const
1392 {
1393         return colinfo_[col].skip_;
1394 }
1395
1396 void InsetMathGrid::doDispatch(Cursor & cur, FuncRequest & cmd)
1397 {
1398         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1399
1400         Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
1401
1402         FuncCode const act = cmd.action();
1403         switch (act) {
1404
1405         // insert file functions
1406         case LFUN_LINE_DELETE_FORWARD:
1407                 cur.recordUndoInset();
1408                 //autocorrect_ = false;
1409                 //macroModeClose();
1410                 //if (selection_) {
1411                 //      selDel();
1412                 //      break;
1413                 //}
1414                 if (nrows() > 1)
1415                         delRow(cur.row());
1416                 if (cur.idx() > cur.lastidx())
1417                         cur.idx() = cur.lastidx();
1418                 if (cur.pos() > cur.lastpos())
1419                         cur.pos() = cur.lastpos();
1420                 break;
1421
1422         case LFUN_CELL_SPLIT:
1423                 cur.recordUndo();
1424                 splitCell(cur);
1425                 break;
1426
1427         case LFUN_CELL_BACKWARD:
1428                 // See below.
1429                 cur.selection(false);
1430                 if (!idxPrev(cur)) {
1431                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1432                         cur.undispatched();
1433                 }
1434                 break;
1435
1436         case LFUN_CELL_FORWARD:
1437                 // Can't handle selection by additional 'shift' as this is
1438                 // hard bound to LFUN_CELL_BACKWARD
1439                 cur.selection(false);
1440                 if (!idxNext(cur)) {
1441                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1442                         cur.undispatched();
1443                 }
1444                 break;
1445
1446         case LFUN_NEWLINE_INSERT: {
1447                 cur.recordUndoInset();
1448                 row_type const r = cur.row();
1449                 addRow(r);
1450
1451                 // split line
1452                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1453                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1454
1455                 // split cell
1456                 splitCell(cur);
1457                 if (ncols() > 1)
1458                         swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1459                 if (cur.idx() > 0)
1460                         --cur.idx();
1461                 cur.pos() = cur.lastpos();
1462                 cur.forceBufferUpdate();
1463                 //mathcursor->normalize();
1464                 //cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1465                 break;
1466         }
1467
1468         case LFUN_TABULAR_FEATURE: {
1469                 cur.recordUndoInset();
1470                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1471                 istringstream is(to_utf8(cmd.argument()));
1472                 string s;
1473                 is >> s;
1474                 if (s == "valign-top")
1475                         setVerticalAlignment('t');
1476                 else if (s == "valign-middle")
1477                         setVerticalAlignment('c');
1478                 else if (s == "valign-bottom")
1479                         setVerticalAlignment('b');
1480                 else if (s == "align-left")
1481                         setHorizontalAlignment('l', cur.col());
1482                 else if (s == "align-right")
1483                         setHorizontalAlignment('r', cur.col());
1484                 else if (s == "align-center")
1485                         setHorizontalAlignment('c', cur.col());
1486                 else if (s == "append-row")
1487                         for (int i = 0, n = extractInt(is); i < n; ++i)
1488                                 addRow(cur.row());
1489                 else if (s == "delete-row") {
1490                         cur.clearSelection(); // bug 4323
1491                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1492                                 delRow(cur.row());
1493                                 if (cur.idx() >= nargs())
1494                                         cur.idx() -= ncols();
1495                         }
1496                         cur.pos() = 0; // trick, see below
1497                 }
1498                 else if (s == "copy-row") {
1499                         // Here (as later) we save the cursor col/row
1500                         // in order to restore it after operation.
1501                         row_type const r = cur.row();
1502                         col_type const c = cur.col();
1503                         for (int i = 0, n = extractInt(is); i < n; ++i)
1504                                 copyRow(cur.row());
1505                         cur.idx() = index(r, c);
1506                 }
1507                 else if (s == "swap-row") {
1508                         swapRow(cur.row());
1509                         // Trick to suppress same-idx-means-different-cell
1510                         // assertion crash:
1511                         cur.pos() = 0;
1512                 }
1513                 else if (s == "add-hline-above")
1514                         rowinfo_[cur.row()].lines_++;
1515                 else if (s == "add-hline-below")
1516                         rowinfo_[cur.row()+1].lines_++;
1517                 else if (s == "delete-hline-above")
1518                         rowinfo_[cur.row()].lines_--;
1519                 else if (s == "delete-hline-below")
1520                         rowinfo_[cur.row()+1].lines_--;
1521                 else if (s == "append-column") {
1522                         row_type const r = cur.row();
1523                         col_type const c = cur.col();
1524                         for (int i = 0, n = extractInt(is); i < n; ++i)
1525                                 addCol(cur.col() + 1);
1526                         cur.idx() = index(r, c);
1527                 }
1528                 else if (s == "delete-column") {
1529                         cur.clearSelection(); // bug 4323
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                                 delCol(col(cur.idx()));
1534                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1535                         cur.pos() = 0; // trick, see above
1536                 }
1537                 else if (s == "copy-column") {
1538                         row_type const r = cur.row();
1539                         col_type const c = cur.col();
1540                         copyCol(cur.col());
1541                         cur.idx() = index(r, c);
1542                 }
1543                 else if (s == "swap-column") {
1544                         swapCol(cur.col());
1545                         cur.pos() = 0; // trick, see above
1546                 }
1547                 else if (s == "add-vline-left") {
1548                         colinfo_[cur.col()].lines_++;
1549                         if (!colinfo_[cur.col()].special_.empty())
1550                                 colinfo_[cur.col()].special_ += '|';
1551                 }
1552                 else if (s == "add-vline-right") {
1553                         colinfo_[cur.col()+1].lines_++;
1554                         if (!colinfo_[cur.col()+1].special_.empty())
1555                                 colinfo_[cur.col()+1].special_.insert(0, 1, '|');
1556                 }
1557                 else if (s == "delete-vline-left") {
1558                         colinfo_[cur.col()].lines_--;
1559                         docstring & special = colinfo_[cur.col()].special_;
1560                         if (!special.empty()) {
1561                                 docstring::size_type i = special.rfind('|');
1562                                 LASSERT(i != docstring::npos, break);
1563                                 special.erase(i, 1);
1564                         }
1565                 }
1566                 else if (s == "delete-vline-right") {
1567                         colinfo_[cur.col()+1].lines_--;
1568                         docstring & special = colinfo_[cur.col()+1].special_;
1569                         if (!special.empty()) {
1570                                 docstring::size_type i = special.find('|');
1571                                 LASSERT(i != docstring::npos, break);
1572                                 special.erase(i, 1);
1573                         }
1574                 }
1575                 else {
1576                         cur.undispatched();
1577                         break;
1578                 }
1579                 // perhaps this should be FINISHED_BACKWARD -- just for clarity?
1580                 //lyxerr << "returning FINISHED_LEFT" << endl;
1581                 break;
1582         }
1583
1584         case LFUN_CLIPBOARD_PASTE:
1585                 parseflg |= Parse::VERBATIM;
1586                 // fall through
1587         case LFUN_PASTE: {
1588                 if (cur.currentMode() != MATH_MODE)
1589                         parseflg |= Parse::TEXTMODE;
1590                 cur.message(_("Paste"));
1591                 cap::replaceSelection(cur);
1592                 docstring topaste;
1593                 if (cmd.argument().empty() && !theClipboard().isInternal())
1594                         topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
1595                 else {
1596                         idocstringstream is(cmd.argument());
1597                         int n = 0;
1598                         is >> n;
1599                         topaste = cap::selection(n, buffer().params().documentClassPtr());
1600                 }
1601                 InsetMathGrid grid(buffer_, 1, 1);
1602                 if (!topaste.empty())
1603                         if ((topaste.size() == 1 && isAscii(topaste))
1604                             || !mathed_parse_normal(grid, topaste, parseflg)) {
1605                                 resetGrid(grid);
1606                                 mathed_parse_normal(grid, topaste, parseflg | Parse::VERBATIM);
1607                         }
1608
1609                 bool hline_enabled = false;
1610                 FuncRequest fr = FuncRequest(LFUN_TABULAR_FEATURE, "add-hline-above");
1611                 FuncStatus status;
1612                 if (getStatus(cur, fr, status))
1613                         hline_enabled = status.enabled();
1614                 if (grid.nargs() == 1) {
1615                         // single cell/part of cell
1616                         cur.recordUndoInset();
1617                         cur.cell().insert(cur.pos(), grid.cell(0));
1618                         cur.pos() += grid.cell(0).size();
1619                         if (hline_enabled)
1620                                 rowinfo_[cur.row()].lines_ += grid.rowinfo_[0].lines_;
1621                         else {
1622                                 for (unsigned int l = 0; l < grid.rowinfo_[0].lines_; ++l) {
1623                                          cur.cell().insert(0,
1624                                                 MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1625                                          cur.pos()++;
1626                                 }
1627                         }
1628                 } else {
1629                         // multiple cells
1630                         cur.recordUndoInset();
1631                         col_type const numcols =
1632                                 min(grid.ncols(), ncols() - col(cur.idx()));
1633                         row_type const numrows =
1634                                 min(grid.nrows(), nrows() - cur.row());
1635                         for (row_type r = 0; r < numrows; ++r) {
1636                                 for (col_type c = 0; c < numcols; ++c) {
1637                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1638                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1639                                 }
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                                                 idx_type i = index(r + cur.row(), 0);
1645                                                 cell(i).insert(0,
1646                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1647                                         }
1648                                 }
1649                                 // append the left over horizontal cells to the last column
1650                                 idx_type i = index(r + cur.row(), ncols() - 1);
1651                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1652                                         cell(i).append(grid.cell(grid.index(r, c)));
1653                         }
1654                         // append the left over vertical cells to the last _cell_
1655                         idx_type i = nargs() - 1;
1656                         for (row_type r = numrows; r < grid.nrows(); ++r) {
1657                                 for (col_type c = 0; c < grid.ncols(); ++c)
1658                                         cell(i).append(grid.cell(grid.index(r, c)));
1659                                 if (hline_enabled)
1660                                         rowinfo_[r].lines_ += grid.rowinfo_[r].lines_;
1661                                 else {
1662                                         for (unsigned int l = 0; l < grid.rowinfo_[r].lines_; ++l) {
1663                                                 cell(i).insert(0,
1664                                                         MathAtom(new InsetMathUnknown(from_ascii("\\hline"))));
1665                                         }
1666                                 }
1667                         }
1668                 }
1669                 cur.clearSelection(); // bug 393
1670                 // FIXME audit setBuffer calls
1671                 cur.inset().setBuffer(*buffer_);
1672                 cur.forceBufferUpdate();
1673                 cur.finishUndo();
1674                 break;
1675         }
1676
1677         case LFUN_LINE_BEGIN:
1678                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1679                 // fall through
1680         case LFUN_LINE_BEGIN_SELECT:
1681                 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1682                                 act == LFUN_WORD_LEFT_SELECT ||
1683                                 act == LFUN_LINE_BEGIN_SELECT);
1684                 cur.macroModeClose();
1685                 if (cur.pos() != 0) {
1686                         cur.pos() = 0;
1687                 } else if (cur.idx() % cur.ncols() != 0) {
1688                         cur.idx() -= cur.idx() % cur.ncols();
1689                         cur.pos() = 0;
1690                 } else if (cur.idx() != 0) {
1691                         cur.idx() = 0;
1692                         cur.pos() = 0;
1693                 } else {
1694                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1695                         cur.undispatched();
1696                 }
1697                 break;
1698
1699         case LFUN_LINE_END:
1700                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1701                 // fall through
1702         case LFUN_LINE_END_SELECT:
1703                 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1704                                 act == LFUN_WORD_RIGHT_SELECT ||
1705                                 act == LFUN_LINE_END_SELECT);
1706                 cur.macroModeClose();
1707                 cur.clearTargetX();
1708                 if (cur.pos() != cur.lastpos()) {
1709                         cur.pos() = cur.lastpos();
1710                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1711                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1712                         cur.pos() = cur.lastpos();
1713                 } else if (cur.idx() != cur.lastidx()) {
1714                         cur.idx() = cur.lastidx();
1715                         cur.pos() = cur.lastpos();
1716                 } else {
1717                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1718                         cur.undispatched();
1719                 }
1720                 break;
1721
1722         default:
1723                 InsetMathNest::doDispatch(cur, cmd);
1724         }
1725 }
1726
1727
1728 bool InsetMathGrid::getStatus(Cursor & cur, FuncRequest const & cmd,
1729                 FuncStatus & status) const
1730 {
1731         switch (cmd.action()) {
1732         case LFUN_TABULAR_FEATURE: {
1733                 string s = cmd.getArg(0);
1734                 if (&cur.inset() != this) {
1735                         // Table actions requires that the cursor is _inside_ the
1736                         // table.
1737                         status.setEnabled(false);
1738                         status.message(from_utf8(N_("Cursor not in table")));
1739                         return true;
1740                 }
1741                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1742                         status.setEnabled(false);
1743                         status.message(from_utf8(N_("Only one row")));
1744                         return true;
1745                 }
1746                 if (ncols() <= 1 &&
1747                     (s == "delete-column" || s == "swap-column")) {
1748                         status.setEnabled(false);
1749                         status.message(from_utf8(N_("Only one column")));
1750                         return true;
1751                 }
1752                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1753                      s == "delete-hline-above") ||
1754                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1755                      s == "delete-hline-below")) {
1756                         status.setEnabled(false);
1757                         status.message(from_utf8(N_("No hline to delete")));
1758                         return true;
1759                 }
1760
1761                 if ((colinfo_[cur.col()].lines_ == 0 &&
1762                      s == "delete-vline-left") ||
1763                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1764                      s == "delete-vline-right")) {
1765                         status.setEnabled(false);
1766                         status.message(from_utf8(N_("No vline to delete")));
1767                         return true;
1768                 }
1769                 if (s == "valign-top" || s == "valign-middle" ||
1770                     s == "valign-bottom" || s == "align-left" ||
1771                     s == "align-right" || s == "align-center") {
1772                         status.setEnabled(true);
1773                         char const ha = horizontalAlignment(cur.col());
1774                         char const va = verticalAlignment();
1775                         status.setOnOff((s == "align-left" && ha == 'l')
1776                                         || (s == "align-right"   && ha == 'r')
1777                                         || (s == "align-center"  && ha == 'c')
1778                                         || (s == "valign-top"    && va == 't')
1779                                         || (s == "valign-bottom" && va == 'b')
1780                                         || (s == "valign-middle" && va == 'c'));
1781                         return true;
1782                 }
1783                 if (s == "append-row" || s == "delete-row" ||
1784                     s == "copy-row" || s == "swap-row" ||
1785                     s == "add-hline-above" || s == "add-hline-below" ||
1786                     s == "delete-hline-above" || s == "delete-hline-below" ||
1787                     s == "append-column" || s == "delete-column" ||
1788                     s == "copy-column" || s == "swap-column" ||
1789                     s == "add-vline-left" || s == "add-vline-right" ||
1790                     s == "delete-vline-left" || s == "delete-vline-right") {
1791                         status.setEnabled(true);
1792                 } else {
1793                         status.setEnabled(false);
1794                         status.message(bformat(
1795                             from_utf8(N_("Unknown tabular feature '%1$s'")),
1796                             from_utf8(s)));
1797                 }
1798
1799 #if 0
1800                 // FIXME: What did this code do?
1801                 // Please check whether it is still needed!
1802                 // should be more precise
1803                 if (v_align_ == '\0') {
1804                         status.enable(true);
1805                         break;
1806                 }
1807                 if (cmd.argument().empty()) {
1808                         status.enable(false);
1809                         break;
1810                 }
1811                 if (!contains("tcb", cmd.argument()[0])) {
1812                         status.enable(false);
1813                         break;
1814                 }
1815                 status.setOnOff(cmd.argument()[0] == v_align_);
1816                 status.setEnabled(true);
1817 #endif
1818                 return true;
1819         }
1820
1821         case LFUN_CELL_SPLIT:
1822                 status.setEnabled(cur.idx() != cur.lastidx());
1823                 return true;
1824
1825         case LFUN_CELL_BACKWARD:
1826         case LFUN_CELL_FORWARD:
1827                 status.setEnabled(true);
1828                 return true;
1829
1830         default:
1831                 break;
1832         }
1833         return InsetMathNest::getStatus(cur, cmd, status);
1834 }
1835
1836
1837 // static
1838 char InsetMathGrid::colAlign(HullType type, col_type col)
1839 {
1840         switch (type) {
1841         case hullEqnArray:
1842                 return "rcl"[col % 3];
1843
1844         case hullMultline:
1845         case hullGather:
1846                 return 'c';
1847
1848         case hullAlign:
1849         case hullAlignAt:
1850         case hullXAlignAt:
1851         case hullXXAlignAt:
1852         case hullFlAlign:
1853                 return "rl"[col & 1];
1854
1855         case hullUnknown:
1856         case hullNone:
1857         case hullSimple:
1858         case hullEquation:
1859         case hullRegexp:
1860                 return 'c';
1861         }
1862         // avoid warning
1863         return 'c';
1864 }
1865
1866
1867 //static
1868 int InsetMathGrid::colSpace(HullType type, col_type col)
1869 {
1870         int alignInterSpace = 0;
1871         switch (type) {
1872         case hullUnknown:
1873         case hullNone:
1874         case hullSimple:
1875         case hullEquation:
1876         case hullMultline:
1877         case hullGather:
1878         case hullRegexp:
1879                 return 0;
1880
1881         case hullEqnArray:
1882                 return 5;
1883
1884         case hullAlign:
1885                 alignInterSpace = 20;
1886                 break;
1887         case hullAlignAt:
1888                 alignInterSpace = 0;
1889                 break;
1890         case hullXAlignAt:
1891                 alignInterSpace = 40;
1892                 break;
1893         case hullXXAlignAt:
1894         case hullFlAlign:
1895                 alignInterSpace = 60;
1896                 break;
1897         }
1898         return (col % 2) ? alignInterSpace : 0;
1899 }
1900
1901
1902 } // namespace lyx